| Author |
confusion on overriding variables
|
Soni Prasad
Ranch Hand
Joined: Mar 09, 2005
Posts: 97
|
|
output is 10 10 10 10 20 10 I am confused that as variables are not overriden, at line number 1 reference type of object o is testOver then why output from line 1 is not 20? As abc() is being called on testOver reference then variable of testOver class should be printed which is 20. Please explain...
|
SCJP 1.4, SCBCD 1.3
|
 |
Soni Prasad
Ranch Hand
Joined: Mar 09, 2005
Posts: 97
|
|
|
I am eagerly waiting for some explanation. Please explain...
|
 |
Rohan Kayan
Ranch Hand
Joined: Sep 17, 2004
Posts: 123
|
|
As we are calling the method which is in class A only variable those are in the class A or in the parent class of A will only be accessible from that method . That is why it is printing 10 10 10 .
|
SCWCD 1.4, SCJP 1.4
|
 |
Rajee Dhana
Greenhorn
Joined: May 11, 2005
Posts: 2
|
|
|
try to override the method abc() in testOver class, and see the difference.
|
 |
Andrey Khashin
Greenhorn
Joined: Mar 29, 2005
Posts: 1
|
|
Originally posted by Soni Prasad: output is 10 10 10 10 20 10 I am confused that as variables are not overriden, at line number 1 reference type of object o is testOver then why output from line 1 is not 20? As abc() is being called on testOver reference then variable of testOver class should be printed which is 20. Please explain...
Look here for the same problem solution http://www.coderanch.com/t/248529/java-programmer-SCJP/certification/accessing-variables-methods-polymorphic-way
|
 |
Jeff Hu
Greenhorn
Joined: Feb 03, 2005
Posts: 16
|
|
Originally posted by Soni Prasad:
Let's go through our code, see its run-time behavour. testOver IS-A A. Check instance variable a, we noticed that it has default access. method abc() is in class A. //1 testOver Object o is created with a = 20, BUT a = 10 in Class is also there on the stack. //2 A Object p is created with a = 10. //3 p invokes abc(). this is clear i guess.. printout 10 //4 o invokes abc(). Since there is no overriden abc(), it can only see instance var a belonging to the class which contains abc() method... printout 10 //5 reference variable q of type A is created refering to object of type testOver. //6 q invokes abc(). For the same reason as //4, it prints out 10 //7 access instance variable a. We only look at object referece type, so p is reference type A -> p.a = 10; o is reference type testOver -> o.a = 20; q is reference type A -> q.a =10. output is 10 10 10 10 20 10 If we modify testOver class (add method abc() to overide its super abc()), do similar analysis before. We have output 10 20 20 10 20 10
|
SCJP 1.4, SCJA 1.0
|
 |
Soni Prasad
Ranch Hand
Joined: Mar 09, 2005
Posts: 97
|
|
Thanx alot! now its clear to me soni.
|
 |
 |
|
|
subject: confusion on overriding variables
|
|
|