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 教师闺蜜祝福语简短