Search code examples
javainheritanceconstructorextendssuper

super.a = b instead of super(b)


I'm learning the super keyword and accidentally get this, here's an example :

    public class A {
       double a;
       public A (double a) {
          this.a = a;
       }
    }
    public class B extends A {
       public B (double b) {
          super.a = b;  //***
       }
    }

The usual way to do this as in the tutorials is super(b) to reusing its parent constructor, but what is wrong with super.a = b?


Solution

  • When you write your class A like this:

    public class A {
        double a;
        public A(double a) {
            this.a = a;
        }
    }
    

    you overwrite the default constructor and in the line this.a = a you are accessing instance variable and setting the values and in class B:

    public class B extends A {
        public B(double b) {
            super.a = b; // ***
        }
    }
    

    you are trying to access instance variables of Class B through the constructor because super.a in here , the super referes to the constructor and its wrong and throwing the Implicit super constructor A() is undefined. Must explicitly invoke another constructor which means: in Class B its looking for a constructor which has no parameter because you overwrite the default constructor of class and it can't recognize it by calling super.a = b so you have to call the super constructor as a function and in the first line of code:

    public class B extends A {
        public B(double b) {
            super(b);
            super.a = b; // ***
        }
    }