Java 编译时多态性和运行时多态性的区别
多态性是面向对象编程中最重要的概念之一。它是通过在多种方式上执行单一任务的概念。有两种类型的多态性,一种是编译时多态性,另一种是运行时多态性。
方法重载是编译时多态性的示例,而方法重写是运行时多态性的示例。
Sr. No. | Key | 编译时多态性 | 运行时多态性 |
---|---|---|---|
1 | Basic | 编译时多态性意味着绑定发生在编译时 | 运行时多态性,在运行时我们知道将要调用哪个方法 |
2 | Static/DynamicBinding | 可以通过静态绑定实现 | 可以通过动态绑定实现 |
4. | 继承 | 不涉及继承 | 涉及继承 |
5 | 示例 | 方法重载是编译时多态性的一个示例 | 方法重写是运行时多态性的一个示例 |
编译时多态的示例
public class Main {
public static void main(String args[]) {
CompileTimePloymorphismExample obj = new CompileTimePloymorphismExample();
obj.display();
obj.display("Polymorphism");
}
}
class CompileTimePloymorphismExample {
void display() {
System.out.println("In Display without parameter");
}
void display(String value) {
System.out.println("In Display with parameter" + value);
}
}
运行时多态性的示例
public class Main {
public static void main(String args[]) {
RunTimePolymorphismParentClassExample obj = new RunTimePolymorphismSubClassExample();
obj.display();
}
}
class RunTimePolymorphismParentClassExample {
public void display() {
System.out.println("Overridden Method");
}
}
public class RunTimePolymorphismSubClassExample extends RunTimePolymorphismParentExample {
public void display() {
System.out.println("Overriding Method");
}
}