Any way to _not_ call superclass constructor in Java?

后端 未结 13 1314
误落风尘
误落风尘 2020-12-15 04:16

If I have a class:

class A {
   public A() { }
}

and another

class B extends A {
   public B() { }
}

is t

13条回答
  •  醉梦人生
    2020-12-15 04:33

    I had a similar requirement where I needed my child class NOT to go through the super class' constructor, and I wanted the rest of the benefits of the super class. Since super class is also mine, here's what I did.

    class SuperClass {
        protected SuperClass() {
            init();
        }
    
        // Added for classes (like ChildClassNew) who do not want the init to be invoked.
        protected SuperClass(boolean doInit) {
            if (doInit)
                init();
        }
    
        //
    }
    
    class ChildClass1 extends SuperClass {
        ChildClass1() {
            // This calls default constructor of super class even without calling super() explicitly.
            // ...
        }
        // ....
    }
    
    class ChildClass2 extends SuperClass {
        ChildClass2() {
            // This calls default constructor of super class even without calling super() explicitly.
            // ...
        }
        // ....
    }
    
    class ChildClassNew extends SuperClass {
        ChildClassNew() {
            /*
             * This is where I didn't want the super class' constructor to 
             * be invoked, because I didn't want the SuperClass' init() to be invoked.
             * So I added overloaded the SuperClass' constructor where it diesn;t call init().
             * And call the overloaded SuperClass' constructor from this new ChildClassNew.
             */
            super(false);
            // 
            // ...
        }
        // ....
    }
    

提交回复
热议问题