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 ..