Pad*_*abh 21 java overriding overloading
我们总是说方法重载是静态多态,而重写是运行时多态.静态到底是什么意思?在编译代码时是否解析了对方法的调用?那么正常方法调用和调用最终方法之间的区别是什么?哪一个在编译时链接?
RHS*_*ger 23
方法重载意味着根据输入创建函数的多个版本.例如:
public Double doSomething(Double x) { ... }
public Object doSomething(Object y) { ... }
Run Code Online (Sandbox Code Playgroud)
在编译时选择调用哪种方法.例如:
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
Run Code Online (Sandbox Code Playgroud)
方法重写是指通过原始子类定义方法的新版本
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
Run Code Online (Sandbox Code Playgroud)
我希望有所帮助
Boz*_*zho 11
你是对的 - 在编译时实现对重载方法的调用.这就是为什么它是静态的.
根据调用方法的类型,在运行时实现对重写方法的调用.
在Java中,默认情况下所有非静态方法都是"虚函数".只有标记有关键字final的方法才是非虚拟的.
final 方法不能被覆盖,因此它们是静态实现的.
想象一下这个方法:
public String analyze(Interface i) {
i.analyze();
return i.getAnalysisDetails();
}
Run Code Online (Sandbox Code Playgroud)
编译器不能为Interface可能传递给它的所有实现重载此方法.
我不认为你可以调用重载任何类型的多态.重载方法在编译时链接,这种方法排除了将其称为多态.
多态性是指在对派生类对象使用基类引用时,方法与其调用的动态绑定.重写方法是如何实现此多态行为.
| 归档时间: |
|
| 查看次数: |
13515 次 |
| 最近记录: |