1. //Person p = new Student(); // Person父类 Student子类
    2. //System.out.println(p instanceof Person); // instanceof判断p对象是否能使用父类方法
    3. // 继承是is关系,组合是has关系。
    4. public class Object1 {
    5. public static void main(String[] args) {
    6. //Person p = new Person("小王",24);
    7. //Student s = new Student("莉莉",21,100);
    8. PrimaryStudent m = new PrimaryStudent("莉莉",21,100,5);
    9. //System.out.println(p.getAge());
    10. //System.out.println(s.getAge());
    11. System.out.println(m.getScore());
    12. }
    13. }
    14. class Person{
    15. protected String name; // protected允许子类访问父类的字段和方法
    16. protected int age;
    17. public Person(String name,int age){
    18. this.name = name;
    19. this.age = age;
    20. }
    21. public String getName(){
    22. return name;
    23. }
    24. public int getAge(){
    25. return age;
    26. }
    27. }
    28. class Student extends Person{
    29. protected int score;
    30. public Student(String name,int age,int score){
    31. super(name,age); // 调用父类的构造方法Person(String name,int age)
    32. this.score = score;
    33. }
    34. public int getScore(){
    35. return score;
    36. }
    37. }
    38. class PrimaryStudent extends Student{
    39. protected int grade;
    40. public PrimaryStudent(String name,int age,int score,int grade){
    41. super(name,age,score);
    42. this.grade = grade;
    43. }
    44. public int getGrade(){
    45. return grade;
    46. }
    47. }