class HelloWorld
{
public static void main(String[] args)
{
A a = new B();
System.out.println(a.getX());
a.show();
}
}
class A {
int x = 10;
public A() {
}
public int getX() {
return x;
}
public void show(){
System.out.println("A show");
}
}
class B extends A{
int x = 20 ;
public B() {
super();
}
@Override
public void show(){
System.out.println("B show");
}
}
Why is the output this?
10
B Show
I understand 'B Show'. Since the object is of class B, it will call the method that is overridden in B. But do not understand why it is printing '10' in output even though the object of B has value of x equal to 20. Please help me understand this.
extends A {}means.xbut are completely separate fields. In real code you should never do this; it's very confusing.int x;from your B class means B still has a field of typeintnamedx- it inherits that one from A. It just means it now doesn't also have a second field also namedxalso of typeint.The 'name' of a method in java is not just the method name, it also includes the parameter types. You can't override' unless they match. In other words:
Here B's
foomethod is not the same name as A's and therefore foo does not override. If you slap an@Overrideon it, you'll get a compiler error. It is not possible to cause B's foo code to run withA a = new B(); a.foo(5);because given that the reference here (a- a pointer, variables point at objects) is of typeA, the compiler doesn't know about B'sfoo(long)method and thus couldn't possibly call it here. Make that B methodvoid foo(int x)and that is an override andA a = new B(); a.foo(5);would call B's, not A's, because java does dynamic dispatch.The same principle applies to fields. With
A a = new B();a.xrefers to thexfield defined in class A.