编译时多态和运行时多态之间的区别
多态性是最重要的OOP概念之一。它是一个概念,通过它我们可以以多种方式执行单个任务。多态有两种类型,一种是编译时多态,另一种是运行时多态。
方法重载是编译时多态的示例,方法重载是运行时多态的示例。
Compiletimepolymorphismmeansbindingisoccuringatcompiletime
绑定
Itcanbeachievedthroughstaticbinding
Inheritanceisnotinvolved
Methodoverloadingis anexampleofcompiletimepolymorphism
编译时多态性的示例
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");
}
}