例如,我们编写两个类,一个是Pupil类(小学生),一个是Graduate(大学毕业生)
问题:两个类的属性和方法有很多是相同的,怎么办?
改进前
package student;
//小学生->模拟小学生考试情况
public class Pupil {
public String name;
public int age;
private double score;//成绩
public void setScore(double score) {
this.score = score;
}
public void testing(){
System.out.println("小学生 " + name + " 正在考小学数学..");
}
public void showInfo() {
System.out.println("学生名 " + name + " 年龄 " + age + " 成绩 " + score);
}
}
package student;
//大学生类-> 模拟大学生考试的简单情况
public class Graduate {
public String name;
public int age;
private double score;//成绩
public void setScore(double score) {
this.score = score;
}
public void testing() {//和Pupil不一样
System.out.println("大学生 " + name + " 正在考大学数学..");
}
public void showInfo() {
System.out.println("学生名 " + name + " 年龄 " + age + " 成绩 " + score);
}
}
package student;
public class Test {
public static void main(String[] args) {
Pupil pupil = new Pupil();
pupil.name = "银角大王";
pupil.age = 10;
pupil.testing();
pupil.setScore(60);
pupil.showInfo();
System.out.println("===========================");
Graduate graduate = new Graduate();
graduate.name = "金角大王";
graduate.age = 22;
graduate.testing();
graduate.setScore(100);
graduate.showInfo();
}
}
解决方案:继承,提高代码复用性!
改进后
package student;
//父类,是Pupil 和 Graduate的父类
public class Stu {
//共有属性
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);
}
}
package student;
//小学生->模拟小学生考试情况
//让Pupil 继承 Student类
public class Pupil extends Stu {
public void testing() {
System.out.println("小学生 " + name + " 正在考小学数学..");
}
}
package student;
//大学生类-> 模拟大学生考试的简单情况
public class Graduate extends Stu {
public void testing() {//和Pupil不一样
System.out.println("大学生 " + name + " 正在考大学数学..");
}
}
package student;
public class Test {
public static void main(String[] args) {
Pupil pupil = new Pupil();
pupil.name = "银角大王";
pupil.age = 10;
pupil.testing();
pupil.setScore(60);
pupil.showInfo();
System.out.println("===========================");
Graduate graduate = new Graduate();
graduate.name = "金角大王";
graduate.age = 22;
graduate.testing();
graduate.setScore(100);
graduate.showInfo();
}
}