aspose file tools*
The moose likes Beginning Java and the fly likes what is the reason behind this Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "what is the reason behind this" Watch "what is the reason behind this" New topic
Author

what is the reason behind this

Arpit Chaudhary
Greenhorn

Joined: Dec 28, 2007
Posts: 7
class Parent {
����String message = "parent";
}

class Child extends Parent {
����String message = "child";
}

public class Test {
����public static void main(String[] args) {
��������Parent yo = new Child();
��������System.out.println(yo.message);
����}
}

output of this program is
parent

please clarify the thing why "child" should not be print while object is Child class and reference is Parent class.

Thanks in advance
Arpit
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
Because fields are not overridden; the only members which are overridden are accessible (public, protected, or default access in the same package) instance members.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19787
    
  20

Don't you mean "the only members which are overridden are accessible (public, protected, or default access in the same package) instance methods."?

For all others you are hiding the original. In your example, Child actually has two fields called message. The one from parent can be accessed using "super.message". You can only go up one parent class like this, and only to accessible fields.

For instance, if you define a subclass like this:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Arpit Chaudhary
Greenhorn

Joined: Dec 28, 2007
Posts: 7
means..
Binding of instance member except overriden method depends on type of reference variable not on actual object.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19787
    
  20

Exactly!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
Originally posted by Rob Prime:
Don't you mean . . . instance methods."?
Yes, my spelling really was bad, wasn't it?

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: what is the reason behind this