• Post Reply Bookmark Topic Watch Topic
  • New Topic

Working with inheritance  RSS feed

 
Urs Waefler
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the code: I do not understand why it prints 8. I would kindly ask for a clarification.
 
Mark Spencers
Ranch Hand
Posts: 51
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because instance variables CANNOT be overridden in Java. In Java only methods can be overridden.

When you declare a field with the same name as an existing field in a superclass, the new field hides the existing field. The existing field from the superclass is still present in the subclass, and can even be used ... subject to the normal Java access rules
 
Urs Waefler
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that the object determines which instance variable is used. Thus I do not fully understand this code yet.
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. The formal type of your reference determines which field is used:

Same object, different formal types.
 
Urs Waefler
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it is an instance field, then the reference determines which instance it is.

If it is an instance method, then the object determines which method it is.

Is this a correct understanding?
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could explain it that way. Here's how these concepts are actually called.

The formal type of a variable determines which field to access.

The actual type of a variable determines which method to access.

Here's the difference between formal type and actual type:

The formal type of car is Car. The actual type of car is SportsCar.

When the actual type is used to determine which member is accessed, that member is called virtual. In Java, fields are never virtual, and instance methods are always virtual.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another way to think of it is that field references are not polymorphic, only instance methods are. So, when you reference a field directly, the binding of that reference is done at compile time (static binding) using the declared type (what Stephan refers to as the "formal" type). With instance methods, the binding happens at runtime (dynamic binding) and is based on the object's actual runtime type.

See the difference between static and dynamic binding in Java
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!