Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Help with static overriding behavior and hiding variables  RSS feed

 
Shridhar Raghavan
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



OUTPUT


Hi. In MethodOverridingClass
Hi. In MethodOverridingClass
10
10
--------------
Hi. In ExtendedOverridingClass
Hi. In MethodOverridingClass
10
10
Hi. In ExtendedOverridingClass
Hi. In ExtendedOverridingClass
20
20



Hi,

As you can see above i am trying to figure out the behavior of inheritance wrt static methods and variables. I wanted to know

1- The behavior of inherited variables. As you can see the final variable in the superclass are overriden in the subclass
2- The behavior of static methods invoked in the case of an instance of a derived class. For example, am lost at why the program prints out "In MethodOverridingClass" while creating the second object.
 
Mohamed Sanaulla
Bartender
Posts: 3179
34
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might want to read this OverridingVsHiding
 
Shridhar Raghavan
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The link explains method overriding and hiding. Can you help out with variable hiding.

Also i get the the compiler looks at the declared type to invoke the class method. But it still doesn't explain what happened when i created the second object.
 
Rob Spoor
Sheriff
Posts: 21090
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And we can't tell you because you haven't given us the code for ExtendedOverridingClass.
 
Shridhar Raghavan
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Rob Spoor
Sheriff
Posts: 21090
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shridhar Raghavan wrote:1- The behavior of inherited variables. As you can see the final variable in the superclass are overriden in the subclass

No it is not. If you have read the article Mohamed linked to you would have seen that the final variable is hidden, not overridden. You cannot override variables, nested classes or static methods. Only instance methods can be overridden. All else is hidden (or shadowed) instead.

2- The behavior of static methods invoked in the case of an instance of a derived class. For example, am lost at why the program prints out "In MethodOverridingClass" while creating the second object.

Because with hidden methods and variables, the reference type determines which method is called, not the actual type. In constructors, the reference type is always that of the class itself.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!