• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is the reason behind this

 
Arpit Chaudhary
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Arpit Chaudhary
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
means..
Binding of instance member except overriden method depends on type of reference variable not on actual object.
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exactly!
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rob Prime:
Don't you mean . . . instance methods."?
Yes, my spelling really was bad, wasn't it?

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic