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 好听的元旦简短祝福语