What is the output of the following code?
class Base { String var = "Main"; void printVar() { System.out.println(var); } } class Derived extends Base { String var = "AAA"; void printVar() { System.out.println(var); } } class Main { public static void main(String[] args) { Base base = new Base(); Base derived = new Derived(); System.out.println(base.var); System.out.println(derived.var); base.printVar(); derived.printVar(); } }
a Main Main Main AAA b Main AAA Main AAA c Main Main Main Main d Main AAA AAA AAA
A
The following line of code refers to an object of the class Base, using a reference variable of type Base. Hence, both of the following lines of code print Main:
System.out.println(base.var); base.printVar();
The following line of code refers to an object of the class Derived using a reference variable of type Base:
Base derived = new Derived();
Because the instance variables bind at compile time, the following line accesses and prints the value of the instance variable defined in the class Base:
System.out.println(derived.var); // prints Main
In derived.printVar(), the method printVar is called using a reference of type Base, invoking on a Derived object and so executes the overridden printVar method in the class Derived.
class Base {//from w ww . j av a 2 s . c o m String var = "Main"; void printVar() { System.out.println(var); } } class Derived extends Base { String var = "AAA"; void printVar() { System.out.println(var); } } class Main { public static void main(String[] args) { Base base = new Base(); Base derived = new Derived(); System.out.println(base.var); System.out.println(derived.var); base.printVar(); derived.printVar(); } }