Raven221221221
Raven221221221

Reputation: 142

Wrong usage of 'super' in extending class constructors

I thought I understood what super does, however I can't understand why in the following code

class test {
    int i;

    test(int i){
    this.i = i;
}

}    
class testSub extends test{ 

    testSub(int i) {
        super(i);
    }

    /*testSub(int i) {
        this.i = i;
    }*/
}

why wouldn't the second constructor (commmented) work? it is doing the same thing..

Thank you for any clarifications :)

EDIT: Thanks to everyone - sorry I can't mark more answers. Also sorry if this shouldn't be an edit.

A quick recap: Since testSub is a child of parent test, even though the constructor does the same thing, the child needs to consist of its parent part. Only if test had the default constructor this would be possible. If I didn't get it right please respond.

Upvotes: 1

Views: 61

Answers (4)

SLaks
SLaks

Reputation: 887385

As the error clearly tells you, you must call a base class constructor, or the base class will not be constructed.

Doing the same thing as the base class constructor is not enough; you must actually call it.

If the base class has a parameterless constructor (eg, the default constructor provided if you don't write any), you can leave it out, and the compiler will automatically call it.

Upvotes: 1

candied_orange
candied_orange

Reputation: 7334

Doing the same thing is not the same as being the same thing. The compiler isn't going to check that you took care of what super is supposed to do. It's just going to insist that you call it when it's required.

Upvotes: 0

Paul Boddington
Paul Boddington

Reputation: 37645

Your class test has an explicit constructor. You must use this constructor in a constructor of every sub class.

If test did not have an explicit constructor, an implicit constructor with no arguments would be generated, and you wouldn't have to explicitly invoke this in the sub class. In this situation, your second constructor would be perfectly valid.

class test {
    int i;
}

class testSub extends test{ 

    testSub(int i) {
        this.i = i;
    }
}

Upvotes: 1

SJuan76
SJuan76

Reputation: 24865

The constructor of your class will always call one of the superclass constructors.

You can make the call explicit with super (first instruction of the constructor), and in that case you can chose which constructor you will call.

If you do not explicitly use super, it will try to use the default (parameterless) constructor. But your superclass do not have it, so it will fail to compile.

The easiest solution is to explicitly declare the parameterless constructor in your superclass. That said, it is always better to use the parent methods when possible, so, if in the end the result is the same, it is more elegant using super(i).

Upvotes: -1

Related Questions