Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in Object Reference

 
N.Senthil Kumar
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
obj.getMethod(); will call getMethod of B - Since Overriding.

may i know why obj.i prints A's instance variable rather than B's

Thanks in advance.
 
Alex Parvan
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, please use the code tags, it's easier to read your code
Second, methods can override each other, but fields get accessed by the object you created.
In your code: A obj = new B(); the object obj is of type A, that means obj.i gets the field "i" from A. If you change your code to B obj = new B(); then obj.i calls the field "i" from B, because obj is now type B.
 
N.Senthil Kumar
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Parvan Alexandru wrote:First of all, please use the code tags, it's easier to read your code
Second, methods can override each other, but fields get accessed by the object you created.
In your code: A obj = new B(); the object obj is of type A, that means obj.i gets the field "i" from A. If you change your code to B obj = new B(); then obj.i calls the field "i" from B, because obj is now type B.


Thanks Parvan Alexandru .

I also just came to know the Answer.

fields get accessed by the reference you created.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49466
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is because polymorphism only applies to instance methods. It does not apply to fields or static members. You have shown two examples of bad design: fields not labelled "private" and hiding fields by having a field with the same name in the subclass as in the superclass.
 
N.Senthil Kumar
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:That is because polymorphism only applies to instance methods. It does not apply to fields or static members. You have shown two examples of bad design: fields not labelled "private" and hiding fields by having a field with the same name in the subclass as in the superclass.


Thank You Campbell Ritchie.

Its an Interview Question. Not my Program.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49466
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You would have had a better chance of getting the job if you had pointed out the two examples of bad code. It did look to me like bad code put there intentionally, so you can comment about it when you answer.

At least I think I was correct about "polymorphism only applies to instance methods".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic