下面的类是Human的父类,拥有两个属性和两个获取接口。

    1. package com.yuque.phil616.oop.extend;
    2. public class Human {
    3. String name;
    4. int age;
    5. /*
    6. * Every human have a name.
    7. * Every human have an age.
    8. * students and teachers are human.
    9. * however their own properties are not common.
    10. * we can know more at https://www.runoob.com/java/java-inheritance.html
    11. * */
    12. public int getAge() {
    13. return age;
    14. }
    15. public String getName() {
    16. return name;
    17. }
    18. }

    下面的Student类继承了Human类,因为学生是人类的子类,人类拥有的两个属性:姓名和年龄学生也有,而学生拥有的两个属性:学号和班级并不是所有人类都有的,因此学生类继承了人类,保留了人类的属性和方法,同时也增加了自己的属性。

    1. package com.yuque.phil616.oop.extend;
    2. public class Student extends Human{
    3. int studentNumber;
    4. int classNumber;
    5. /*
    6. * a student is a human, so it has name and age;
    7. * however, as a student, it should have student number and classes number
    8. * this is extend
    9. * */
    10. @Override
    11. public int getAge() {
    12. return super.getAge();
    13. }
    14. @Override
    15. public String getName() {
    16. return super.getName();
    17. }
    18. public int getClassNumber() {
    19. return classNumber;
    20. }
    21. public int getStudentNumber() {
    22. return studentNumber;
    23. }
    24. }

    同理下面的Teacher类也有人类的属性,也有属于自己的属性。

    1. package com.yuque.phil616.oop.extend;
    2. public class Teacher extends Human{
    3. String department;
    4. int salary;
    5. /*
    6. * teacher is a human,but not all the human have salary and department name;
    7. * */
    8. @Override
    9. public String getName() {
    10. return super.getName();
    11. }
    12. @Override
    13. public int getAge() {
    14. return super.getAge();
    15. }
    16. public int getSalary() {
    17. return salary;
    18. }
    19. public String getDepartment() {
    20. return department;
    21. }
    22. }