Reputation: 21
Can someone explain why the output is 10 and not 20? Why does the object refers to the value of the parent class instead of the class it is assigned to?
class A {
int i = 10;
}
class B extends A {
int i = 20;
}
public class MainClass {
public static void main(String[] args) {
A a = new B();
System.out.println(a.i);
}
}
Upvotes: 1
Views: 70
Reputation: 2740
In Java, methods are overridden not variables. So variables belong to their owner classes. a
is a reference of type A
that point to an object of type B
but remains of type A
.
To call the i
of B
, you have to cast a
to B
.
A a = new B();
System.out.println(((B)a).i);
Upvotes: 1
Reputation: 7175
Variables can not be overridden in Java as they are resolved at compile-time; You can use super
to set its values,
class A {
int i = 10;
}
class B extends A {
int i = 20;
public B() {
super();
super.i = i;
}
}
A a = new B();
System.out.println(a.i); //20
Upvotes: 1
Reputation: 32028
Can someone explain why the output is 10 and not 20?
Since the value of i
is defined in the class A
and is NOT overridden/re-assigned by the definition of class B
as you might just be assuming. Adding a custom constructor could clarify your doubts further of what you might be intending to do:
class A {
int i = 10;
}
class B extends A {
public B() {
this.i = 20;
}
}
A a = new B();
System.out.println(a.i); // would now print 20
Declaring the same variable i
in class B
would have its own scope and does not inherit from the class A
.
Upvotes: 1
Reputation: 314
The instance you're creating is of type A
, so since both variables have the same name, you'll get the superclass' one, if you want B
's you should do
B b = new B()
System.out.println(b.i)
You shouldn't use variables of the same name like that in between superclasses and subclasses, gets very confusing and kinda defeats the purpose of inheriting.
Upvotes: 2