Java中的方法重载和方法重写之间有什么区别?
以下是重载和覆盖之间的显着差异。
方法重载
在方法重载中,一个类有两个或多个名称相同且参数不同的方法。
在重载中,两种方法的返回类型都可能不同。
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
方法覆盖
在方法覆盖中,超类和子类具有名称相同的方法,包括参数。
在重写中,返回类型也应该相同。
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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短