Reputation: 27375
Consider
class MyClass{
public MyClass(Integer i){}
}
class MyExtendedClass extends MyClass{
public MyExtendedClass(SomeType s){ ... }//Compile error if SomeType!=Integer
public MyExtendedClass(Integer i){
super(i);
...
}
}
Why we cant define constructor of MyExtendedClass
with signature different from MyClass's constructor? Why we must call a constructor of superclass firstly?
Upvotes: 2
Views: 846
Reputation: 5207
Your constructor can have a different signature. But you must call one of super constructors. This is how Java works, see the Java Language Specification.
Alternative 1: You can call a static method, like following:
public MyExtendedClass(SomeType s){ super(convertToInt(s)); }
private Integer convertToInt(SomeType st){ ... }
Alternative 2: Use composition / delegate instead of inheritance.
class MyExtendedClass [
private MyClass delegate;
public MyExtendedClass(SomeType s){
do what you want
delegate = new MyClass(...);
}
public void doSomething(... params){
delegate.doSomething(params);
}
Upvotes: 0
Reputation: 213223
Why we cant define constructor of MyExtendedClass with signature different from MyClass's constructor?
You can of course do it. The error you are getting is for a different reason.
Why we must call a constructor of superclass firstly?
Because that is how the objects of your class are initialized. An object's state comprise of all the fields in it's own class, plus all the non-static fields of all the superclasses.
So, when you create an instance, the state should be initialized for all the superclasses and then finally of it's own class. That is why the first statement of a constructor should be super()
chaining to the superclass constructor, or this()
chain to it's own class constructor.
The reason your code probably failed is, you are trying to call the superclass constructor with string argument. But there is no such constructor currently. The super class has just a single constructor taking an int
argument. Also, adding super()
would not work too. Because your superclass doesn't have a 0-arg constructor.
Try changing your constructor to:
public MyExtendedClass(SomeType s){
super(0);
}
and it would work. Alternatively, add a 0-argument constructor to your super class, and leave the subclass constructor as it is. It would also work in that case.
Suggested Read:
Upvotes: 1
Reputation: 2629
You can define a constructor with a different signature. But in the constructor of the subclass you have to call the constructor of the base class. The base class needs to initialize itself (e.g. its private members) and there is no other way to do it other than by calling one of its constructors.
Upvotes: 2