我们总是说方法重载是静态多态性,而重写是运行时多态性。我们在这里所说的静态到底是什么意思?在编译代码时是否会解析对方法的调用?那么,普通方法调用和调用最终方法有什么不同呢?哪一个是在编译时链接的?
发布于 2010-03-18 20:46:42
方法重载意味着基于输入生成函数的多个版本。例如:
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
我希望这对你有帮助
发布于 2010-03-18 20:40:57
我不认为你可以调用重载任何形式的多态性。重载的方法是在编译时链接的,这在某种程度上排除了调用它的多态性。
多态性是指当您为派生类对象使用基类引用时,方法与其调用的动态绑定。覆盖方法是实现这种多态行为的方式。
发布于 2012-09-12 01:14:00
简单定义-方法重载处理在同一个类中有两个或更多具有相同名称但不同参数的方法(函数)的概念。
而方法覆盖意味着有两个方法具有相同的参数,但实现不同。其中一个将存在于父类(基类)中,而另一个将存在于派生类(子类)中。为此需要.@Override注释。
https://stackoverflow.com/questions/2469767
复制相似问题