Hi guys, I have one issue with one exercise. It has this code:
what does it print?
Now, you know how we often say, "the test asks for something but it might be asking in fact something else etc", I thought that variables in interfaces are public final so when I saw in the interface and then in the class implementing the interface I thought, well that's it, it won't compile. But in fact, the correct answer here is "It will print 0 when TestClass is run."
SO why is it that we can change the value of location?
As Stephan van Hulst said When a Super type and a sub type has variable with same name, variable hiding will be introduced. That means Sub type variable hides the super type variable. In such case you need to explicitly call the super type variable . Below is the sample program to understand it.
In your example, move,moveBack methods operate on location variable in Donkey class. So location variable Movable interface doesn't get changed.
Here object is Donkey type and reference type (m) is Movable.
It prints 0 . Because m is Movable type. When Super type and Sub type contains a variable with same name , Variable will be called based on reference type. If reference type is Super type, variable in super type will be called and If reference type is sub type, variable in sub type will be called.
Hope it helps !
posted 3 years ago
Ah, I understand :-), thanks guys! So the problem will occur only if I try to change the value of the variable declared in the parent interface, won't it?
Jason Attin wrote:So the problem will occur only if I try to change the value of the variable declared in the parent interface, won't it?
Yes, here is an example to illustrate that
If you remove field age of Demo then final field age of DemoInterface will not be hidden anymore in that case dm1.age = 100; will also give CE because It'll be final field age of DemoInterface.