class A { public static void main(String[] args)
{ A a = new A();
B b = new B();
A ab = new B();
System.out.format("%d %d %d %d %d %d", a.x, b.x, ab.x, a.y, b.y, ab.y); }
int x = 2;
int y = 3;
A(int x) { this.x = x; }
A() { this(7); } }
class B extends A {
int y = 4;
B() { super(6);
}
Hey all, I was just looking through some examples from my course and came across this problem that stumped me.
I realize that
that this code should print out
"7 6 6 3 4 3"
But why is ab.y equal to 3? Isn't the "real" type of object ab of class B? Which then would lead me to believe that ab.y be 4?
As a consequence of there being a type hierarchy, a variable of one type may refer to an object whose actual type is one of that type's subtypes. The type given when the variable was declared is referred to as the apparent type of the object referred to by the variable.
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
So, a Java class is by default package-private.
The default access specifier is an important differentiate between classes and structs. It is public by default for structs and private by default for classes.
Because you are accessing the fields directly, and not via getter methods.
You cannot override fields, only methods.
Class B
has a field y
in addition to the one in parent class A
. The two fields do not interfere with each-other, which one gets picked up is determined at compile-time (by the type known to the compiler).
If you say
A ab = new B();
then
ab.y
will be compiled to look at the field y
declared in class A
. This is not dispatched at runtime to the real instance's class. It would be the same with a static method.
If you do
B ab = new B();
then you get the field in class B
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With