天天看点

Java super关键字的使用Person类Student类测试类

1. super理解为:父类的

2. super可以用来调用:属性、方法、构造器

3. super的使用

3.1我们可以在子类的方法或构造器中。通过使用"super.属性"或"super.方法"的方式,显式的调用父类中声明的属性或方法。但是,通常情况下,我们习惯省略"super."

3.2特殊情况:当子类和父类中定义了同名的属性时,我们要想在子类中调用父类中声明的属性,则必须显式的使用"super.属性"的方式,表明调用的是父类中声明的属性。

3.3特殊情况:当子类重写了父类中的方法以后,我们想在子类的方法中调用父类中被重写的方法时,则必须显式的使用"super.方法"的方式,表明调用的是父类中被重写的方法。

Person类

package com.binbin.test02;

public class Person {
	int id = 1001;
	String name;
	int age;
	
	public Person() {
		
	}

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public void eat() {
		System.out.println("人可以吃饭");
	}

}           

复制

Student类

测试package com.binbin.test02;

public class Student extends Person {

	int id = 2001;
	char sex;

	public Student() {
	}

	public Student(String name, int age, char sex) {
		super(name, age); // 构造器使用super的方法
		this.sex = sex;
	}

	public void showInfo() {
		System.out.println("this id:" + this.id + ", name: " + name + ", sex:" + sex + ", age: " + age);
		System.out.println("super id " + super.id);
		this.eat(); // 当前类的eat方法
		System.out.println();
		super.eat(); // 父类的eat方法
	}

	@Override
	public void eat() {
		System.out.println("重写:人可以吃有营养的饭~~");
	}
}           

复制

测试类

package com.binbin.test02;

public class SuperTest {
	public static void main(String[] args) {
		Student s = new Student();
		s.showInfo();
		
		Student s1 = new Student("Tom", 32, '男');
		s1.showInfo();
	}
}           

复制

Java super关键字的使用Person类Student类测试类

运行结果