Two Laptop Bag*
The moose likes Java in General and the fly likes Question about inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Question about inheritance" Watch "Question about inheritance" New topic
Author

Question about inheritance

Kaustav Ganguly
Greenhorn

Joined: Dec 14, 2009
Posts: 28
I dont know if this question or doubt I am having is already answered before in this forum, so please excuse me if it has been or if it is a sily question. But I could not understand the behaviour of the following code snippets.



And the output was

10Test
20TestChild1

I could not understand why test.a and test.b would print the superclass value but when we invoke the method it is the other way round. Really confused.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37923
    
  22
Methods might be polymorphic, but fields aren't. Start with this FAQ, and if that doesn't help, ask again.
Pranav Raulkar
Ranch Hand

Joined: Apr 20, 2011
Posts: 73

Hi Kaustav,
Casting an object to a parent class is called upcasting and is done automatically. If you upcast an object, it will lose all it's properties, which were inherited from below it's current position. Hence test.a and test.b prints out the parent data from its parent class. Note, that data will not be lost, you just can't use it, until you downcast to the right level. Why this behavior? Because in inheritance parent class knows nothing about its child class properties, but the child class knows about its parent data as it inherited it.

To overcome this, what you need to do is use polymormism. Polymorphism uses automatic downcast during method calls. Which is what happened in the getValues method (overriden method). As test contains a reference to child object it calls child's getValues (after downcasting) where trivially, the child data is printed.
Kaustav Ganguly
Greenhorn

Joined: Dec 14, 2009
Posts: 28
I understood that for static methods instance does no make any difference. But what for instance variable ? Instance variables are specific to a particular instance, why are they as per the declaration ?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37923
    
  22
Didn't it say anything about fields in the FAQ?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37923
    
  22
No, it didn't say anything about fields. Fields are hidden, rather like static members.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Question about inheritance
 
Similar Threads
Garbage Collection and Post Increment Operator doubts
equals() and hashCode()
whats wrong with my code ?
can a sub class reference access private variable of super class?
Using Enumerations