Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

shadowing

 
taras khoma
Greenhorn
Posts: 9
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


why the result is "parent"?
 
Stephan van Hulst
Bartender
Posts: 6337
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't override fields. The title of this thread implies you're already familiar with the concept.
 
taras khoma
Greenhorn
Posts: 9
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes I'm familiar but we have object of type Child and not of type Parent.
And in java fields are accessible not by object but by reference(no polymorphism)

So take previous considerations we have object of type Child(NOT Parent) and invoke its method. So it must out Child field.
But in real we receive Parent field.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But you aren't accessing message via a Child reference. You're calling say() on a Child reference. That executes the code in Parent (because the method is not overridden in Child), and that's where you access message.
 
Nomaan Butt
Ranch Hand
Posts: 54
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Before subclass object getting instantiated the super class constructor gets called and its object gets instatiated. As say() method is not being overridden there super class say() mehod is being called and there it is using message field of its own. If you override the say() method in the subclass then it will be called.
 
naveen yadav
Ranch Hand
Posts: 384
Java MyEclipse IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My arguments are simple Java facts :

fact 1: Child class have inherited the say() from parent. True
fact 2: To call the method of a class one must use object of that class. True
fact 3: Child object is created and inherited say() is called . True
fact 4: say() of Parent is called . Why?
 
Nomaan Butt
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Naveen,

say() of Parent class is called as say() is not overloaded in Child.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic