What is the result of compiling and running the following code?

class Base {
    public String name = "Base";
    public String getName() {
        return name;
    }
}

class Sub extends Base {
    public String name = "Sub";
    public String getName() {
        return name;
    }
}

public class Program {
    public static void main(String[] args) {
        Sub s = new Sub();
        Base b = s;
        System.out.println(b.name);
    }
}
Explanation
When accessing the fields the link type is used and not the a real object. If instead of turning to the field a call to get the value of the overridden method field was made thanks to the late binding we would get the value of the real object.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Cosmo
Sign Up Now
or Subscribe for future quizzes