28--方法的重写(override/overwrite)

在子类中可以根据需要对从父类中继承来的方法进行改造,也称 为方法的重置、覆盖。在程序执行时,子类的方法将覆盖父类的方法。

  1. 子类重写的方法必须和父类被重写的方法具有相同的方法名称、参数列表
  2. 子类重写的方法的返回值类型不能大于父类被重写的方法的返回值类型
  3. 子类重写的方法使用的访问权限不能小于父类被重写的方法的访问权限
    注意:子类不能重写父类中声明为private权限的方法
  4. 子类方法抛出的异常不能大于父类被重写方法的异常
  5. 子类与父类中同名同参数的方法必须同时声明为非static的(即为重写),或者同时声明为 static的(不是重写)。因为static方法是属于类的,子类无法覆盖父类的方法。
  6. 返回值类型:
    1)父类被重写的方法的返回值类型是void,则子类重写的方法的返回值类型只能是void
    2)父类被重写的方法的返回值类型是A类型,则子类重写的方法的返回值类型可以是A类或A类的子类
    3)父类被重写的方法的返回值类型是基本数据类型(比如:float),则子类重写的方法的返回值类型必须是相同的基本数据类型(必须也是float)
    实例1:定义分类
package com.qwy.bean;
public class Person {
    
    
	public void sayHello(){
    
    
		System.out.println("Person.sayHello()");;
	}
}

实例2:定义子类

package com.qwy.bean;
public class Student extends Person{
    
    
	public void sayHello(){
    
    
		System.out.println("Student.sayHello()");
	}
}

实例3:测试

package com.qwy.test;
import com.qwy.bean.Student;
public class TestDemo {
    
    
	public static void main(String[] args) {
    
    
		Student student= new Student();
		student.sayHello();
	}
}

运行结果:
Student.sayHello()

从运行结果看,运行的是被子类覆写过的方法。

猜你喜欢

转载自blog.csdn.net/qwy715229258163/article/details/114441280