I have two classes:
public class ClassA {
public void method(Number n) {
System.out.println(\"ClassA: \" + n + \" \" + n.getClass());
}
}
To clear I added, show()
method in both classA
and classB
.
public void show() {
System.out.println(getClass());
}
I call like this,
// Case 1
ClassA a = new ClassB();
a.method(3);// ClassA: 3 class java.lang.Integer
a.show(); // class ClassB
// Case 2
ClassB b = new ClassB();
b.method(3);// ClassB: 3 class java.lang.Integer
b.show(); // class ClassB
Here method(Number n) and method(Integer d) have different signatures. It is not overriding. It is overloading.
But show() method is method overriding.
In case 1, Only methods of class A are accessible with object a. a is type classA, methods in classB are not visible. That's why your classA method is called. But for show() method as it is overridden method, class B's show() method is called.
In case 2, Both methods of class A and B are accessible with object b as ClassB extends ClassA.