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 送给学长毕业祝福语简短