多态性是最重要的OOP概念之一。它是一个概念,通过它我们可以以多种方式执行单个任务。多态有两种类型,一种是编译时多态,另一种是运行时多态。
方法重载是编译时多态的示例,方法重载是运行时多态的示例。
| 序号 | 键 | 编译时多态 | 运行时多态 |
|---|---|---|---|
| 1个 | 基本的 | Compile time polymorphism means binding is occuring at compile time | R un time多态性,在运行时我们知道要调用哪种方法 |
| 2 | 静态/动态 绑定 | | 可以通过动态绑定来实现 |
| 4。 | 继承 | Inheritance is not involved | 涉及继承 |
| 5 | 例 | Method overloading is an example of compile time polymorphism | 方法覆盖是运行时多态性的一个示例 |
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");
}
}