简体   繁体   中英

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?

A sub-class's constructor calls the constructor of its super-class ( A in your case). If your sub-class B has no constructor, the compiler automatically creates a constructor without any parameters. That constructor automatically calls the constructor with no parameters of the base class A .

Since your base class A has a constructor with a parameter, the compiler does not generate a constructor without parameters for it, and therefore you must explicitly create a matching constructor with a single parameter in your sub class B.

The are other alternatives to creating that constructor in B :

You can define a no parameters constructor in A :

public A()
{
   this.inrt = 0;
}

This will allow the no parameters constructor automatically generated for B to call the matching constructor in A .

Or you can explicitly define a no parameters constructor in B that calls the existing constructor of A :

public B()
{
    super(0);
}

If there is no constructor, there is default constructor, which also calls super's default constructor. But when you created constructor in parent, there is no default constructor in parent.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM