Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'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?

like image 484
peakit Avatar asked Dec 08 '25 08:12

peakit


1 Answers

Because all Java method invocations that are not explicitly super invocations are dispatched to the most derived class, even in superclass constructors. This means that superclasses get the benefit of subclass behaviors, but it also means that overriding methods can theoretically get invoked before the constructor in that class.

like image 53
John Calsbeek Avatar answered Dec 09 '25 22:12

John Calsbeek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!