首页 > 其他分享 >动手动脑:方法覆盖

动手动脑:方法覆盖

时间:2022-10-10 18:37:47浏览次数:39  
标签:System 覆盖 动脑 PrintDemo method 动手 Grandparent public out

注:方法覆盖要求子类与父类的方法一模一样,否则就是方法重载(overload)

测试:

1.  在子类中,若要调用父类中被覆盖的方法,可以使用super关键字。

package test2;

class Grandparent {

	public Grandparent() {

		System.out.println("GrandParent Created.");

	}

	public void PrintDemo() {
		System.out.println("学习");
	}
}

class Parent extends Grandparent {

	public Parent() {

		System.out.println("Parent Created");

	}
	@Override
	public void PrintDemo() {
		// TODO Auto-generated method stub
		super.PrintDemo();
		System.out.println("Java");
	}

}

public class TestInherits {

	public static void main(String args[]) {

		Parent p = new Parent();
		p.PrintDemo();

	}

}

  

结果:

GrandParent Created.
Parent Created
学习
Java

  

2.  

(1)覆盖方法的允许访问范围不能小于原方法。

如: 改为protected

@Override
	protected void PrintDemo() {
		// TODO Auto-generated method stub
		super.PrintDemo();
		System.out.println("Java");
	}

报错:

Multiple markers at this line
- Cannot reduce the visibility of the inherited method from
Grandparent
- overrides test2.Grandparent.PrintDemo

(2)覆盖方法所抛出的异常不能比原方法更多。

(3)声明为final方法不允许覆盖。

public final void PrintDemo() {
		System.out.println("学习");
	}

报错:

Multiple markers at this line
- overrides test2.Grandparent.PrintDemo
- Cannot override the final method from
Grandparent

(4)不能覆盖静态方法

public static void PrintDemo() {
		System.out.println("学习");
	}

报错:

Multiple markers at this line
- This instance method cannot override the static method from Grandparent
- The method PrintDemo() of type Parent must override or implement a supertype
method
- overrides test2.Grandparent.PrintDemo

标签:System,覆盖,动脑,PrintDemo,method,动手,Grandparent,public,out
From: https://www.cnblogs.com/ashuai123/p/16776742.html

相关文章