Java Puzzler - Can anyone explain this behavior?

abstract class AbstractBase {
    abstract void print();

    AbstractBase() {
        // Note that this call will get mapped to the most derived class 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 outputs the following output:

Value in Derived1: 0
Value in Derived1: 10

      

I don't understand why the print()

in constructor AbstractBase

always maps to the most derived class (here Derived1

)print()

Why not DerivedClass

print()

? Can anyone help me in understanding this?

+2


source to share


2 answers


Because all Java method calls that do not explicitly call super

invocations are sent to the most derived class, even to the constructors of the superclass. This means that superclasses benefit from the behavior of the subclass, but it also means that overriding methods could in theory be called before the constructor in that class.



+9


source


Virtualization in a superclassic class.



Look at virtualization in the superclass constructor

+2


source







All Articles