面向对象中级-继承
原理示意图
层级目录
父类代码 Student
package com.hspedu.extend_.improve;
//父类
public class Student {
//共有属性
public String name;
public int age;
private double score;
//共有方法
public void setScore(double score) {
this.score = score;
}
public void showInfo(){
System.out.println("学生姓名:" + name + "年龄:" + age + "成绩" + score);
}
}
子类 Pupil
package com.hspedu.extend_.improve;
public class Pupil extends Student {
public void testing(){
System.out.println("小学生" + name + "正在考小学数学...");
}
}
子类 Graduate
package com.hspedu.extend_.improve;
public class Graduate extends Student{
public void testing(){
System.out.println("大学生" + name + "正在考大学数学...");
}
}
主类 Extends01
package com.hspedu.extend_.improve;
public class Extends01 {
public static void main(String[] args) {
Pupil pupil = new Pupil();
pupil.name = "小明~";
pupil.age = 11;
pupil.testing();
pupil.setScore(80);
pupil.showInfo();
System.out.println("=============");
Graduate graduate = new Graduate();
graduate.name = "大明";
graduate.age = 22;
graduate.testing();
graduate.setScore(90);
graduate.showInfo();
}
}
运行结果