I get why a.get()
returns 20, it is because of dynamic binding since object of B is created at runtime so it calls the get()
in class B
But why does a.x
print 10?
class A {
int x = 10;
int get() {
return x;
}
}
class B extends A {
int x = 20;
int get() {
return x;
}
}
class Main {
public static void main(String[] args) {
A a = new B();
System.out.println(a.get()); //20
System.out.println(a.x); //10
}
}
If you could also explain the memory used in storing the object here.