简体   繁体   中英

Static binding and dynamic binding in Java

At first I'm a beginner
I have seen so much tutorials, read so much examples and tried to understand this topic even from the JLS, yet I still have some confusion or misunderstanding.

Let me show you the problem I can't understand.

Imagine we have three classes Parent , Child1 , Child2 as follows:

class Parent {
    void doSmth(Object o) {
        System.out.println("Parent.doSmth");
    }
}

class Child1 extends Parent {
    void doSmth(Object o) {
        System.out.println("Child1.doSmth");
    }
}

class Child2 extends Parent {
    void doSmth(String s) {
        System.out.println("Child2.doSmth");
    }
}

class Test {
    public static void main(String[] args) {
        Parent p1 = new Child1();
        Parent p2 = new Child2();

        p1.doSmth("String");
        p2.doSmth("String");
    }
}

What I understood is, because the references of p1 and p2 are from the type Parent , then doSmth(Object) only will be visible to the compiler.

for p1.doSmth("String"); the compiler didn't bind it because there is an overriding method, so it just left it for the JVM to bind it in the runtime (dynamic binding).

while for p2.doSmth("String"); the compiler bound it because it found no overriding methods for it (static binding).

The question is, Is what I've said true? or do I have a misconception? if it's false, then please tell me what steps does the compiler take in such cases??
And if it's true, how could the compiler expect for p1.doSmth that it has an overriding method (while it doesn't know it's real type), while in p2.doSmth it just bound it?? am I missing something??

I'm sorry but this is really getting me headache ..

Trying to sum up discussion. Edit as required.

Static binding in Java occurs during Compile time while Dynamic binding occurs during Runtime.

At compile time, p1 and p2 both are types of Parent and Parent has doSmth(Object) method hence both lines binds to the same method.

    p1.doSmth("String");
    p2.doSmth("String");

During runtime, dynamic binding comes into picture.

p1 is instance of Child1 and Child1 has overridden doSmth(Object) hence the implementation from Child1 is used.

p2 is instance of Child2 and Child2 does NOT override doSmth(Object) hence the implementation of inherited method from Parent is called.

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