Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Function Call with Overload [duplicate]

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.

like image 283
cceasy Avatar asked Oct 19 '18 08:10

cceasy


1 Answers

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
like image 198
SBylemans Avatar answered Nov 15 '22 16:11

SBylemans