继承后续

方法的重写(override/overwrite)

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

要求:

  1. 子类重写的方法必须和父类被重写的方法具有相同的方法名称、参数列表
  2. 子类重写的方法的返回值类型不能大于父类被重写的方法的返回值类型
  3. 子类重写的方法使用的访问权限不能小于父类被重写的方法的访问权限
    子类不能重写父类中声明为private权限的方法
  4. 子类方法抛出的异常不能大于父类被重写方法的异常

注意:

  • 子类与父类中同名同参数的方法必须同时声明为非static的(即为重写),或者同时声明为static的(不是重写)。因为static方法是属于类的,子类无法覆盖父类的方法。
class Person{
    
    
	String name;
	int age;
	
	public void walk(){
    
    
		System.out.println("Person类的walk方法");
	}
	public void eat(){
    
    
		System.out.println("Person类的eat方法");
	}
}
public class Student extends Person{
    
    
	public void walk(){
    
    
		System.out.println("Student类的walk方法");
	}
	public void eat(){
    
    
		System.out.println("Student类的eat方法");
	}
}

super关键字

在Java类中使用super来调用父类中的指定操作:

  • super可用于访问父类中定义的属性
  • super可用于调用父类中定义的成员方法
  • super可用于在子类构造器中调用父类的构造器

注意:

  • 尤其当子父类出现同名成员时,可以用super表明调用的是父类中的成员
  • super的追溯不仅限于直接父类
  • super和this的用法相像,this代表本类对象的引用,super代表父类的内存空间的标识
class Person{
    
    
	protected String name = "张三";
	protected int age;
	public String getInfo(){
    
    
		return "Name:" + name + "\nage:" + age;
	}
class Student extends Person {
    
    
	protected String name = "李四";
	private String school = "New Oriental";
	public String getSchool() {
    
    
		return school; 
	}
	public String getInfo() {
    
    
		return super.getInfo() + "\nschool: " + school;
	}
}
public class Test {
    
    
	public static void main(String[] args) {
    
    
		Student st = new Student();
		System.out.println(st.getInfo());
	}
}

子类调用父类的构造方法

  • 子类中所有的构造器默认都会访问父类中空参数的构造器
  • 当父类中没有空参数的构造器时,子类的构造器必须通过**this(参数列表)或者super(参数列表)**语句指定调用本类或者父类中相应的构造器。同时,只能”二选一”,且必须放在构造器的首行
  • 如果子类构造器中既未显式调用父类或本类的构造器,且父类中又没有无参的构造器,则编译出错
class Person {
    
    
	private String name;
	private int age;
	private Date birthDate;
	public Person(String name, int age, Date d) {
    
    
		this.name = name;
		this.age = age;
		this.birthDate = d; 
	}
	public Person(String name, int age) {
    
    
		this(name, age, null);
	}
	public Person(String name, Date d) {
    
    
		this(name, 30, d);
	}
	public Person(String name) {
    
    
		this(name, 30);
	}
}
public class Student extends Person {
    
    
	private String school;
	public Student(String name, int age, String s) {
    
    
		super(name, age);
		school = s; 
	}
	public Student(String name, String s) {
    
    
		super(name);
		school = s; 
	}
	// 编译出错: no super(),系统将调用父类无参数的构造器。
	public Student(String s) {
    
     
		school = s; 
	}
}
区别点 this super
访问属性 范文本类中的属性,如果本类没有此属性则从父类中继续查找 直接访问父类中的属性
调用方法 访问本类中的方法,如果本类没有此方法则从父类中继续查找 直接访问父类中的方法
调用构造方法 调用本类构造器,必须放在构造器的首行 调用父类构造器,必须放在子类构造器的首行

猜你喜欢

转载自blog.csdn.net/qq_44346427/article/details/109002714