bharat bhasin wrote:I wrote a program as follows :
public class A {
private void show() {
System.out.println("A()");
}
public void value() {
this.show();
}
public static void main(String[] args) {
A obj = new B();
obj.value();
}
}
class B extends A {
private void show() {
System.out.println("B()");
}
}
I was expecting the output to be this " B () " , but the output comes out to be : "A ()".I don't understand this . . Now after using "this.show()" I expect the method show belonging to class B to be called instead of the method of the class A , because of the following reasons :
1. show() is a private method in class A , so class B doesn't extend it .
2. I have assigned an object of type B to the reference of class A .
3. I am using the "this" operator with show() , so I expect that the method from class B should be called but show from class A is called instead .
Can anyone please this behavior ?
Firstly, good question !!!
1. show() is a private method in class A , so class B doesn't INHERIT it .
3. Consider another example. Forget the value() method for now. focus on showOff1().
The type of obj is A according to our declaration, but its actually B. So, the JVM checks if there is a method showOff1() in A. Good...then it proceeds to check the actual type of obj, which is B. Do we have a VISIBLE showOff1() in B ?
Yes, so execute the showOff1() of B and not of A.
When you look at show(), the same steps are performed. But, there is a difference.
The 'this' is a reference of type A. The JVM sees there if there is a show() in A. It is there. Then proceed to check 2. Is there a show() in B? We know that there is a show() in A and B.
But the code of class A, ie main method cannot see it because its private.
So, the JVM chooses to execute show() of A. <EDIT: Bad choice of words>. The JVM will execute only what is legal/allowed.
Try this - put this code in B and see what happens.