Any way to _not_ call superclass constructor in Java?

后端 未结 13 1316
误落风尘
误落风尘 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:39
    1. As pointed out by another poster, B doesn't extend A, so it won't call A's constructor anyways.

    2. There is no way to do this in Java.

    3. You can probably accomplish equivalently what you want to do as follows:

    a) in each class of your hierarchy, include a constructor with a unique signature that calls the superclass's constructor with its arguments. For example, declare a class "Noop" and a constructor that takes that as an argument:

    public class NoOp {
    }
    
    public class class1 {
        class1() {
            System.out.println("class1() called");
        }
        class1(String x, String y) {
            System.out.println("class1(String, String) called");
    }
        class1(NoOp x) {
            System.out.println("class1(NoOp) called");
        }
    }
    
    public class class2 extends class1 {
        class2() {
            System.out.println("class2() called");
        }
        class2(String x, String y) {
            System.out.println("class2(String, String) called");
    }
        class2(NoOp x) {
            super(x);
            System.out.println("class2(NoOp) called");
        }
    }
    
    public class class3 extends class2 {
        class3() {
            System.out.println("class3() called");
        }
        class3(String x, String y) {
            super(new NoOp());
            System.out.println("class3(String, String) called");
        }
        class3(NoOp x) {
            super(x);
            System.out.println("class3(NoOp) called");
        }
        public static void main(String args[]) {
            class3 x = new class3("hello", "world");
        }
    }
    

    If you run this you will get the output

    class1(NoOp) called
    class2(NoOp) called
    class3(String, String) called
    

    So, effectively you have created a class3 constructor that only calls constructors that don't do anything.

    0 讨论(0)
提交回复
热议问题