I want to know why the third output is NOT b.
Here is my code:
public class SimpleTests {
public void func(A a) {
System.out.println("Hi A");
}
public void func(B b) {
System.out.println("Hi B");
}
public static void main(String[] args) {
A a = new A();
B b = new B();
A c = new B();
SimpleTests i = new SimpleTests();
i.func(a);
i.func(b);
i.func(c);
}
}
class A {}
class B extends A {}
And here is the output:
Hi A
Hi B
Hi A
Could someone tell me why the 3rd output is Hi A
, NOT Hi B
. as the real c is a instance of B.
You're confusing overloading with polymorphism.
With polymorphism, when creating an instance of class B which is a subclass of class A, referenced to by an class A object, and overwrites the method of class A, calling the method will perform the method of class B.
With overloading, the called method only knows the type of the declaration of the argument, not the initialization.
public class A {
public void print() {
System.out.println("A");
}
}
public class B extends A {
@Override
public void print() {
System.out.println("B");
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
B b = new B();
A otherB = new B();
a.print();
b.print();
otherB.print();
}
}
This will output
A
B
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