Search code examples
javaconstructorsubclasssuperclass

Super class Sub class Constructor java


I am new to Java. In the below code I am having some difficulty to understand the concepts.

class A {

    private Integer intr;

    public A(Integer intr) {
        this.inrt = intr;
    }

    public Integer getIntr() {
        return intr;
    }
}

class B extends A {

    public B(Integer intr) { //Eclipse asking me to create this constructor. 
        super(intr);
    }
}

I am getting confused why I need to create that kind of constructor as eclipse suggesting. What is in there?


Solution

  • The only way to instantiate a A is to use the A(Integer) constructor. Unless the super class implements a nullary constructor, every subclass has to explicitely call a super constructor at the beginning of its self constructor.

    But the subclass contructor does not necessarily need the exact same signature. For example, those are also valid:

    public B() {
        super(42);
        // other B specific stuff
    }
    
    public B(Integer i, String s) {
        super(i);
        // other B specific stuff
    }