File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Doubt in Object Reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt in Object Reference" Watch "Doubt in Object Reference" New topic
Author

Doubt in Object Reference

N.Senthil Kumar
Ranch Hand

Joined: Jul 07, 2009
Posts: 50
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.

N.Senthil Kumar
Alex Parvan
Ranch Hand

Joined: Dec 10, 2009
Posts: 115
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.


"Quoting yourself is stupid" - Me
N.Senthil Kumar
Ranch Hand

Joined: Jul 07, 2009
Posts: 50
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

Joined: Oct 13, 2005
Posts: 40052
    
  28
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

Joined: Jul 07, 2009
Posts: 50
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

Joined: Oct 13, 2005
Posts: 40052
    
  28
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".
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in Object Reference