While studying for my finals, I came across the following statement in the book from which I am currently studying. Considering the following code :
class A {
public A(int x) { }
}
class B extends A {
public B(int x ) { }
}
is it mandatory to call the constructor of class A in the constructor of class B(super(x)). The book states that it’s not mandatory, because they have the exact number and type of parameters. But when I try this in a java compiler, the following error gets thrown :
constructor A in class A cannot be
applied to given types; required:
int found: no arguments reason:
actual and formal argument lists
differ in length
The compiler automatically inserts
super()in the beginning.However, even constructors arguments,
super()(without arguments) is added which invokes the default constructor of the superclass. And you don’t have one, hence the error.You have to specify
super(x)(to invokeA(x)), or define a no-argument constructor.By the way, Eclipse compiler gives a way better error message: