java中多态下的覆盖和重载是什么?
Overriding-如果超类和子类具有包含参数的同名方法。JVM根据用于调用方法的对象来调用相应的方法。
即,如果调用该方法的当前对象是超类类型,则执行超类的方法。
或者,如果对象是子类类型,则执行超类的方法。
示例
class SuperClass{
public static void sample(){
System.out.println("Method of the super class");
}
}
public class RuntimePolymorphism extends SuperClass {
public static void sample(){
System.out.println("Method of the sub class");
}
public static void main(String args[]){
SuperClass obj1 = new RuntimePolymorphism();
RuntimePolymorphism obj2 = new RuntimePolymorphism();
obj1.sample();
obj2.sample();
}
}输出结果Method of the super class Method of the sub class
重载-如果一个类有两个或多个具有相同名称和不同参数的方法。在方法调用时,JVM根据传递给它的参数调用相应的方法。
示例
public class OverloadingExample {
public void display(){
System.out.println("Display method");
}
public void display(int a){
System.out.println("Display method "+a);
}
public static void main(String args[]){
OverloadingExample obj = new OverloadingExample();
obj.display();
obj.display(20);
}
}输出结果Display method Display method 20
热门推荐
10 乔迁祝福语简短精辟句子
11 给弟弟敬茶祝福语简短
12 弟媳离职回家祝福语简短
13 送米的祝福语简短
14 送同学的简短祝福语
15 小班老师六一祝福语简短
16 简短的古风生日祝福语
17 元旦祝福语同学简短创意
18 部队牛年祝福语简短的