例如,我们编写两个类,一个是Pupil类(小学生),一个是Graduate(大学毕业生)
问题:两个类的属性和方法有很多是相同的,怎么办?

改进前

  1. package student;
  2. //小学生->模拟小学生考试情况
  3. public class Pupil {
  4. public String name;
  5. public int age;
  6. private double score;//成绩
  7. public void setScore(double score) {
  8. this.score = score;
  9. }
  10. public void testing(){
  11. System.out.println("小学生 " + name + " 正在考小学数学..");
  12. }
  13. public void showInfo() {
  14. System.out.println("学生名 " + name + " 年龄 " + age + " 成绩 " + score);
  15. }
  16. }
  1. package student;
  2. //大学生类-> 模拟大学生考试的简单情况
  3. public class Graduate {
  4. public String name;
  5. public int age;
  6. private double score;//成绩
  7. public void setScore(double score) {
  8. this.score = score;
  9. }
  10. public void testing() {//和Pupil不一样
  11. System.out.println("大学生 " + name + " 正在考大学数学..");
  12. }
  13. public void showInfo() {
  14. System.out.println("学生名 " + name + " 年龄 " + age + " 成绩 " + score);
  15. }
  16. }
  1. package student;
  2. public class Test {
  3. public static void main(String[] args) {
  4. Pupil pupil = new Pupil();
  5. pupil.name = "银角大王";
  6. pupil.age = 10;
  7. pupil.testing();
  8. pupil.setScore(60);
  9. pupil.showInfo();
  10. System.out.println("===========================");
  11. Graduate graduate = new Graduate();
  12. graduate.name = "金角大王";
  13. graduate.age = 22;
  14. graduate.testing();
  15. graduate.setScore(100);
  16. graduate.showInfo();
  17. }
  18. }

image.png
解决方案:继承,提高代码复用性!

改进后

  1. package student;
  2. //父类,是Pupil 和 Graduate的父类
  3. public class Stu {
  4. //共有属性
  5. public String name;
  6. public int age;
  7. private double score;//成绩
  8. //共有的方法
  9. public void setScore(double score) {
  10. this.score = score;
  11. }
  12. public void showInfo() {
  13. System.out.println("学生名 " + name + " 年龄 " + age + " 成绩 " + score);
  14. }
  15. }
  1. package student;
  2. //小学生->模拟小学生考试情况
  3. //让Pupil 继承 Student类
  4. public class Pupil extends Stu {
  5. public void testing() {
  6. System.out.println("小学生 " + name + " 正在考小学数学..");
  7. }
  8. }
  1. package student;
  2. //大学生类-> 模拟大学生考试的简单情况
  3. public class Graduate extends Stu {
  4. public void testing() {//和Pupil不一样
  5. System.out.println("大学生 " + name + " 正在考大学数学..");
  6. }
  7. }
  1. package student;
  2. public class Test {
  3. public static void main(String[] args) {
  4. Pupil pupil = new Pupil();
  5. pupil.name = "银角大王";
  6. pupil.age = 10;
  7. pupil.testing();
  8. pupil.setScore(60);
  9. pupil.showInfo();
  10. System.out.println("===========================");
  11. Graduate graduate = new Graduate();
  12. graduate.name = "金角大王";
  13. graduate.age = 22;
  14. graduate.testing();
  15. graduate.setScore(100);
  16. graduate.showInfo();
  17. }
  18. }

image.png