下面的类是Human的父类,拥有两个属性和两个获取接口。
package com.yuque.phil616.oop.extend;
public class Human {
String name;
int age;
/*
* Every human have a name.
* Every human have an age.
* students and teachers are human.
* however their own properties are not common.
* we can know more at https://www.runoob.com/java/java-inheritance.html
* */
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
下面的Student类继承了Human类,因为学生是人类的子类,人类拥有的两个属性:姓名和年龄学生也有,而学生拥有的两个属性:学号和班级并不是所有人类都有的,因此学生类继承了人类,保留了人类的属性和方法,同时也增加了自己的属性。
package com.yuque.phil616.oop.extend;
public class Student extends Human{
int studentNumber;
int classNumber;
/*
* a student is a human, so it has name and age;
* however, as a student, it should have student number and classes number
* this is extend
* */
@Override
public int getAge() {
return super.getAge();
}
@Override
public String getName() {
return super.getName();
}
public int getClassNumber() {
return classNumber;
}
public int getStudentNumber() {
return studentNumber;
}
}
同理下面的Teacher类也有人类的属性,也有属于自己的属性。
package com.yuque.phil616.oop.extend;
public class Teacher extends Human{
String department;
int salary;
/*
* teacher is a human,but not all the human have salary and department name;
* */
@Override
public String getName() {
return super.getName();
}
@Override
public int getAge() {
return super.getAge();
}
public int getSalary() {
return salary;
}
public String getDepartment() {
return department;
}
}