我正在阅读多态性,经过一番搜索后,我对编译时多态性和运行时多态性的区别感到困惑。
假设我有一个 ABC 类和另一个扩展 ABC 的类, 类 DEF 像这样:
class ABC{
public void myMethod(){
System.out.println("Overridden Method");
}
}
public class DEF extends ABC{
public void myMethod(){
System.out.println("Overriding Method");
}
}
public static void main(String args[]){
ABC obj = new DEF();
obj.myMethod();
}
}
如果我们希望能够用另一个类替换一个类,该类执行相同的任务但以不同的方式无需重新编译调用它们的类, 是方法覆盖方式还是方法重载?
最佳答案
我猜你在问两件事
1) I was reading up on Polymorphism and after some searching I was confused about about the difference of compile-time and run-time polymorphism.
让我们把这里的水分开一点......
在编译时,编译器验证代码并将其转换为字节码。在此阶段解析静态方法调用,因此您知道每次调用静态方法时都会发生相同且唯一的实现。
运行时多态性 是在执行时发生的事情,用于决定要选择给定方法的实际实现。考虑到层次结构中的每个类都提供了这种“多态”方法的一种实现。在幕后,编译器使用称为后期绑定(bind)机制的东西做了大量工作来实现这一目标。
2) If we want to be able to replace a class with another class, which performs the same task but in a different way without having to recompile the class that calls them, Is method overriding the way or method overloading?
您实际上并没有说替换,而是谈论扩展,这就是您在类扩展另一个时所做的事情>。父类中方法的实现可以在子类中被覆盖。 Overload,与层级无关,是用不同的参数集编写相同的方法。
关于java - Java多态的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50547911/