extends of the class with private constructor

后端 未结 3 1777
一生所求
一生所求 2020-11-30 05:39

Suppose we have the following code:

class Test {
    private Test() {
        System.out.println(\"test\");
    }

}

public class One extends Test {

    On         


        
3条回答
  •  执笔经年
    2020-11-30 05:57

    Actually, I found there is a way out. Like this:

    class Base {
        private Base() {
    
        }
    
        public void fn() {
            System.out.println("Base");
        }
    
        public static class Child extends Base {
            public void fn() {
                System.out.println("Child");
            }
        }
    
        public static Base getChild() {
            return new Child();
        }
    }
    

    Now, you can use getChild() to get instance of the extended class.

提交回复
热议问题