我们总是说方法重载是静态多态,重写是运行时多态。这里的静态到底是什么意思?对方法的调用是否在编译代码时解析?那么普通方法调用和调用final方法有什么区别呢?编译时链接的是哪一个?
方法重载意味着根据输入创建函数的多个版本。例如:
public Double doSomething(Double x) { ... }
public Object doSomething(Object y) { ... }
调用哪个方法的选择是在编译时做出的。例如:
Double obj1 = new Double();
doSomething(obj1); // calls the Double version
Object obj2 = new Object();
doSomething(obj2); // calls the Object version
Object obj3 = new Double();
doSomething(obj3); // calls the Object version because the compilers see the
// type as Object
// This makes more sense when you consider something like
public void myMethod(Object o) {
doSomething(o);
}
myMethod(new Double(5));
// inside the call to myMethod, it sees only that it has an Object
// it can't tell that it's a Double at compile time
方法重写意味着通过原始方法的子类定义该方法的新版本
class Parent {
public void myMethod() { ... }
}
class Child extends Parent {
@Override
public void myMethod() { ... }
}
Parent p = new Parent();
p.myMethod(); // calls Parent's myMethod
Child c = new Child();
c.myMethod(); // calls Child's myMethod
Parent pc = new Child();
pc.myMethod(); // call's Child's myMethod because the type is checked at runtime
// rather than compile time
我希望这有帮助
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)