Reputation: 161
while preparing myself for OCJP exam i stumbled upon one question i am unable to wrap my mind around. Here's (a bit modified by me) code from a question:
class Foo {
public int a = 3;
public void addFive() {
a += 5;
System.out.print("f ");
}
}
class Bar extends Foo {
public int a = 8;
public void addFive() {
a += 5;
System.out.print("b ");
}
}
public class TestInheritance {
public static void main(String [] args) {
// part 1
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
// part 2
Bar b = new Bar();
b.addFive();
System.out.println(b.a);
}
}
and the output is:
b 3
b 13
Part 2 i can understand. Nothing surprising here. However part 1 does not let me sleep at night. I understand why Bar.addFive
was run but why in part 1 f.a
prints Foo.a
when I used new Bar()
to instantiate an object? It looks like inheritance works quite different for methods than for variables. What am i missing here to understand that concept? What am I failing in?
Upvotes: 4
Views: 72
Reputation: 217
In order to understand the part 1 you need to understand the difference between static and dynamic binding.
Static binding occurs during compile time and private, final and static methods and variables uses static binding. Static binding uses Type(Class) information for binding.
Based on the above definition when the line Foo f = new Bar(); get compiled, the variable a is initialized 3.
Methods are resolved using Dynamic binding and Dynamic binding uses Object to resolve binding. Since the object is of the Class Bar() the addFive() method of the Bar class is executed. Hence the output b3
Upvotes: 0
Reputation: 2221
Variables are not polymorphic. only methods are.
However you can access them from the parent class if they are declared protected
or public
or through setters and getters
Upvotes: 2
Reputation: 726529
It looks like inheritance works quite different for methods then for variables.
More precisely, inheritance does not make variables polymorphic. When you declare an identical method, a method in the derived class overrides the method in the base. When you declare an identical variable, the variable in the base class is hidden by the variable in the derived class.
In your example, Bar
has two variables a
, but only one method addFive()
. Essentially, each Bar
object holds two integers - Foo.a
and Bar.a
. These two are separate variables. However, the addFive
method is the one defined in Bar
, because it overrides (replaces) addFive
from Foo
.
Note that Java lets Bar
access Foo.addFive
by calling super.addFive()
, but users of Bar
lack this possibility.
Upvotes: 3
Reputation: 121998
Foo f = new Bar();
That line alone means Access the implementations in Bar and members from Foo :)
So you'll get a
from Foo
and the method implementations from Bar
Upvotes: 0