abstract class AbstractBase {
abstract void print();
AbstractBase() {
// Note that this call will get mapped to the most derived class's method
print();
}
}
class DerivedClass extends AbstractBase {
int value = 1;
@Override
void print() {
System.out.println("Value in DerivedClass: " + value);
}
}
class Derived1 extends DerivedClass {
int value = 10;
@Override
void print() {
System.out.println("Value in Derived1: " + value);
}
}
public class ConstructorCallingAbstract {
public static void main(String[] args) {
Derived1 derived1 = new Derived1();
derived1.print();
}
}
The above program produces the following output:
Value in Derived1: 0
Value in Derived1: 10
I am not getting why the print()
in AbstractBase
constructor always gets mapped to the most derived's class (here Derived1
) print()
Why not to DerivedClass
's print()
? Can someone help me in understanding this?