Why can you not inherit from a class whose constructor is private?

前端 未结 6 2087
粉色の甜心
粉色の甜心 2020-12-01 13:39

Why does Java disallow inheritance from a class whose constructor is private?

6条回答
  •  佛祖请我去吃肉
    2020-12-01 13:49

    Java doesn't prevent sub-classing of class with private constructors.

    public class Main {
        static class A {
            private A() {
                System.out.println("Subclassed A in "+getClass().getName());
            }
        }
    
        static class B extends A {
            public B() {
    
            }
        }
    
        public static void main(String... ignored) {
            new B();
        }
    }
    

    prints

    Subclassed A in Main$B
    

    What it prevents is sub-classes which cannot access any constructors of its super class. This means a private constructor cannot be used in another class file, and a package local constructor cannot be used in another package.

    In this situation, the only option you have is delegation. You need to call a factory method to create an instance of the "super" class and wrap it.

提交回复
热议问题