The difference between method rewriting and overloading in Java

 

Method rewriting
Method rewriting occurs during runtime, and the subclass reshapes the internal logic of the method in the parent class, and cannot change the external definition.
Feature
1: Method rewriting occurs in the subclass;
2: The parameters passed in by the rewriting method must be consistent with those in the parent class;
3: The return value type, the method name must be consistent with the parent class, throw The scope of the exception is smaller than the parent class, and the access modifier has greater authority than the parent class;
4: If the access modifier of the parent class method is (private/final/static), the subclass method cannot be overridden;
5: the parent class The construction method cannot be overridden by subclasses;

public class Test{
	public static void main(String[] args) {
		DemoSon demoson=new DemoSon();
		//调用DemoSon类中的dosth()方法
		demoson.dosth(); //输出:DemoSon子类重写的Demo父类的dosth()方法
		Demo1 demo1=new Demo1();
		//直接调用父类Demo的dosth()方法
		demo1.dosth();//输出:Demo父类的方法
	}
}
class Demo{
	public void dosth(){
		System.out.println("Demo父类的方法");
	} 
}
class DemoSon extends Demo{
	public void dosth(){//实现Demo类中dosth()方法的重写
		System.out.println("DemoSon子类重写的Demo父类的dosth()方法");
	} 	
}
class Demo1 extends Demo{
}

Method overloading
Method overloading occurs during compilation. In the same class, multiple methods with the same name perform different logical processing according to different input parameters.
Feature
1: Method overloading must be in the same class;
2: Method parameter lists must be inconsistent (inconsistent types\number\inconsistent order);
3: Method return values ​​and access modifiers can be different;
4: Construction methods can Be overloaded

/*
*	Dome类中实现了dosth()方法的三次重载
*/
public class Dome{
	public void dosth(){
		System.out.ptinln("没有参数的dosth()方法");
	}
	public void dosth(int n){
		System.out.ptinln("一个int类型的参数的dosth()方法");
	}
	public void dosth(int n,String str){
		System.out.ptinln("一个int类型的参数和一个String类型参数的dosth()方法");
	}
}

Guess you like

Origin blog.csdn.net/weixin_51980491/article/details/112724938