问题
I have problem understanding the below code(commented against the line number)
class Base {
void m1(Object o) {
}
void m2(String o) {
}
}
public class Overloading extends Base {
void m1(String s) {
}
void m2(Object o) {
}
public static void main(String[] args) {
Object o = new Object();
Base base1 = new Base();
base1.m1("");//**why this works perfect**
Base base = new Overloading();
base.m2(o);// **why compile time error** - The method m2(String) in the type Base is not applicable for the arguments (Object)
回答1:
Compiler always resolves the method invocation based on the declared type of the reference you invoke it on.
When you invoke the method:
base1.m1("");
compiler looks for the method signature in declared type of base1, which is Base in this case. The matching method in Base is:
void m1(Object o) { }
Since parameter Object can accept a String argument, the invocation is valid. You can pass a subclass object to a superclass reference.
Now, with 2nd invocation:
base.m2(o);
again the declared type of base is Base. And the matching method in Base class is:
void m2(String o) { }
Since you cannot pass an Object reference where a String is accepted. The compiler gives you compiler error. There is no implicit narrowing conversion.
You can understand it more clearly with a simple assignment:
Object ob = new Integer(3);
String str = ob; // This shouldn't be valid
Java doesn't perform implicit narrowing conversion. The assignment from obj to str shouldn't be valid, because else you would get a ClassCastException at runtime.
回答2:
At the line base.m2(o), the compiler doesn't know that base is an Overloading -- it only knows that it is a Base. Why has it forgotten? Because you told it to.
You told the compiler to treat base as a Base, by declaring it with Base base = ....
So, as per your instructions, the compiler will treat base as a Base without knowing anything about any subclass of Base it might or might not extend, and it (correctly) points out that base might not support m2 on an arbitrary Object.
来源:https://stackoverflow.com/questions/18902307/not-able-to-understand-the-inheritance-and-overriding-overloading-in-java