简体   繁体   中英

If my explanation for output is correct

Code:

class TestA {
    public void foo(String... strings ) {
        System.out.println("TestA::foo");
    }

    public void bar(String a){
        System.out.println("TestA::bar");
    }
}

class TestB extends TestA {
    public void foo(String strings ) {
        System.out.println("TestB::foo");
    }

    public void bar(String a){
        System.out.println("TestB::bar");
    }

    public static void main(String[] args) {
        TestA a = new TestB();
        a.foo("foo");
        a.bar("bar");
    }
}

Output is

TestA::foo
TestB::bar

So B::bar is overridden and B::foo is overloaded and when a function is overloaded, it is the data type of the reference that matters not the type of object it is pointing to. Am I right?

TestB class inherits TestA and it has overridden bar method and overloaded foo method, at the time of compiling the TestA a has the reference of the TestB so the overloaded method does not get executed but in the case of overridden bar method a call to overridden method is done at runtime. Because the overloaded method are loaded at compile time and overridden method at runtime.

when a function is overloaded, it is the data type of the reference that matters not the type of object it is pointing to. Am I right?

Yes.

Overloading is compile time binding and only the type of reference is known at that time. While overriding is run time binding and based on type of object the calls are executed.

I'm not sure exactly what your analysis is, but here's what I see:

  • TestA.bar(String) is overridden by TestB.bar(String)
  • TestA.foo(String...) is inherited by TestB and then overloaded in TestB with TestB.foo(String)

However, because the compiler doesn't know that a.foo("foo") is being called for a TestB object, it doesn't know about the overloading. Thus it compiles it into a call to a method with signature foo(String...) . If it knew that a was a TestB , it would bind to foo(String) since that's a closer match (not requiring a conversion to an array argument).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM