重载(Overload)和重写(Override)

重载(Overload)

  • 发生在一个类中
  • 方法名称相同,形参列表不同(形参的个数不同或者形参类型不同),与返回值类型无关
public void test(int a){
	System.out.println("test");
}
public String test(int a,String b){
	System.out.println("test1");
	return "hello";
}

重写(Override)

  • 发生在子类与父类之间
  • 方法名称、返回值类型、形参列表与父类相同
  • 访问限定符要大于等于父类的修饰符
  • 声明为 final 的方法不能重写
  • 重写的好处在于子类可以根据需要,定义自己特定的行为,也就是说,子类可以根据自己的需求实现父类的方法
class Animal{
	public void move(){
		System.out.println("动物可以移动");
	}
}
class Dog extends Animal{
	public void move(){
		System.out.println("狗可以跑");
	}
}
public class Test{
	public static void main(String[] args){
		Animal a = new Animal();
		Animal b = new Dog();//?
		a.move();
		b.move();
	}
}
//执行结果
动物可以移动
狗可以跑

Animal b = new Dog(); 大家可能有疑问,b 属于 Animal 类型,但是运行的是 Dog 类方法。因为在编译阶段,只是检查参数的引用类型,存在 Animal 这个类。而且这个类有 move 方法,所以编译不会报错,到了运行阶段,运行的是 Dog 类型的 move 方法

以下情况编译就会出错

class Animal{
	public void move(){
		System.out.println("动物可以移动");
	}
}
class Dog extends Animal{
	public void move(){
		System.out.println("狗可以跑");
	}
	public void bark(){
		System.out.println("汪汪");
	}
}
public class Test{
	public static void main(String[] args){
		Animal a = new Animal();
		Animal b = new Dog();//?
		a.move();
		b.bark();
	}
}
//编译出错,因为 b 没有 bark 方法
发布了32 篇原创文章 · 获赞 6 · 访问量 804

猜你喜欢

转载自blog.csdn.net/Beverly_/article/details/104544605
今日推荐