Stelios Papamichail
Stelios Papamichail

Reputation: 1290

Uni question regarding overriding and shadowing in java

Today we talked about Overriding and Shadowing in Java and in one of the slides (i've attached it below) we were told to pay close attention to the last 3 lines and make sure we understand what's going on. I'm not sure i do though so i'd like some help or explanation. My understanding is that, since b was explicitly casted to a B object from a D object, calling b.i accesses the current class's i member field which in this case would be the B class's with a value of 6. But when it has to call the f() method which was overriden by D from B, the compiler decided that it should call D's implementation of the f() method because the object was originally a D object(?). I'm really not sure if i've understand this thing right so i'd appreciate your feedback.

P.S: Since both the superclass and the subclass have a variable with the same name and type (i) but without conflict, isn't that shadowing?

slide

Upvotes: 1

Views: 130

Answers (1)

Czarnowr
Czarnowr

Reputation: 93

Case 1:

System.out.println(b.i);

This is variable hiding - "When an instance variable in a subclass has the same name as an instance variable in a super class, then the instance variable is chosen from the reference type."

In your situation, d was cast to B so the instance variable from B is displayed.

Case 2:

System.out.println(b.f());

This is method overriding - "(...) overridden methods completely replace the inherited methods, so when we try to access the method from a parent's reference by holding a child's object, the method from the child class gets called."

More can be found here: https://dzone.com/articles/variable-shadowing-and-hiding-in-java

Upvotes: 1

Related Questions