Reputation: 57
I'd like to know what really happens when somebody calls java super()
method in the constructor of a class that inherits from an abstract class. As we know it, an abstract class cannot be instantiated but super
calls the constructor of the abstract class.
Let's take an example.
public abstract class Figure { // cant be instantiated
private type firstAttribute;
private type secondAttribute;
public Figure(type firstAttribute, type secondAttribute) {
this.fisrtAttribute = fisrtAttribute;
this.fisrtAttribute = fisrtAttribute;
}
protected abstract void anyMethod();
}
class Rectangle extends Figure {
public Rectangle(type firstAttribute, type secondAttribute) {
/*
* call the abstract class constructor but we know, a
* constructor is used to
* instantiate class and we can't instantiate an abstract class
*/
super(firstAttribute, secondAttribute);
// then what really happen ?
}
@override
....
}
Upvotes: 0
Views: 545
Reputation: 744
The confusion stems from the fact that calling the super()
constructor doesn't actually instantiate the super class. It simply invokes the super()
constructor. No more, no less.
This means that the code in the super constructor will be called when super()
is called. You're correct that abstract classes cannot be instantiated, but invoking the super constructor from a subclass constructor doesn't count as instantiation.
Upvotes: 3
Reputation: 8904
The abstract base class initialised any properties you inherit in your concrete inheriting class, so you can avoid code duplication in the initialisation
Upvotes: 1
Reputation: 14999
I executes the code in the constructor it calls.
There is no need to create an instance of the abstract class for that; after all, during constructor invocation, the instance of the class is never created already.
Upvotes: 0