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