What’s the output of the following code?
class A {
public int data=5;
private int pd = 6;
public void print() {
System.out.println(data+pd);
f();
}
protected void f() {
System.out.println(“A::f()”);
}
}
class B extends A {
public int data=2;
private int pd = 3;
public void print() {
super.print();
System.out.println(data+pd);
}
protected void f() {
System.out.println(“B::f()”);
}
}
public class TestAB {
public static void main(String[] args) {
A a = new B();
a.print();
System.out.println(a.data);
}
}
The output is:
11
B::f()
5
5
Well all I know is that the object a is of class B. But the following details are so confusing…Could anybody explain what’s happening with the same variables defined in base and inherited class? Which print()‘ or print()‘s are called?
Thank you for your time.
When you call
a.print();, The print function ofclass Bwill be called. Hope you are clear with that (polymorphism). In the print() method of B class,super.print()is called which in turn has a call to methodf(). Again on polymorphism principle, class B’sf()method will be called.Polymorphism works only on functions. Hence
System.out.println(a.data);in the main function just prints theA classvariable which is 5 and not 2. Hope you understood this.Please refer this link:
http://www.coderanch.com/t/392179/java/java/Polymorphism-data-members