欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

方法的“重载”和“重写”的区别

程序员文章站 2022-06-28 17:06:59
方法的重载是在同一个类中,方法名相同,方法的参数列表不同(参数个数、参数位置、参数的类型),与返回值类型无关方法的重载public static void main(String[] args) {//方法的重载int x=5;int y=7;int z=9;show(x,y);}//两个数的比较public static void show(int x,int y){if(x>y){ System.out.println(x);...

方法的重载是在同一个类中,方法名相同,方法的参数列表不同(参数个数、参数位置、参数的类型),与返回值类型无关
方法的重写是在不同的类中,方法名相同,参数列表相同,返回值类型一致,子类中的权限修饰符要大于或等于父类中的权限修饰符

方法的重载

public static void main(String[] args) {
		//方法的重载
		int x=5;
		int y=7;
		int z=9;
		show(x,y);
	}
	//两个数的比较
	public static void show(int x,int y){
		if(x>y){
	        System.out.println(x);
	    }else{
	        System.out.println(y);
	    }
	}
	
	//三个数比较
	public static void max(int x,int y,int z){
	    if(x>y){
	        if(x>z){
	            System.out.println(x);
	        }else{
	            System.out.println(z);
	        }
	    }else{
	        if(y>z){
	            System.out.println(y);
	        }else{
	            System.out.println(z);
	        }
	    }
	}
	
	/**
	 * 参数类型不同
	 * 一个是int类型,一个是byte类型
	 * @param x
	 * @param y
	 */
	public static void show(int x,byte y){
		if(x>y){
	        System.out.println(x);
	    }else{
	        System.out.println(y);
	    }
	}
	
	/**
	 * 位置不同
	 * 这个要求建立在不同的参数,要是都是一个参数就不行了
	 * @param x
	 * @param y
	 */
	public static void show(byte x,int y){
		if(x>y){
	        System.out.println(x);
	    }else{
	        System.out.println(y);
	    }
	}

方法的重写

	//抽象父类
public abstract class Test1 {
	//虚拟的抽象方法
	public abstract void eat();
	
	public void play(){
		System.out.println("打豆豆");
	}
	//子类
	public class Show extends Test1 {
		/**
		 * 父类是抽象的,所以子类在调用的时候需要重写
		 */
		@Override
		public void eat() {
			System.out.println("吃饭");
		}

	}
}

本文地址:https://blog.csdn.net/starsbloom/article/details/109630627

相关标签: java