JavaSE-10.3.1【继承案例-老师和学生】
1 package day1.yppah03; 2 3 /* 4 3 继承练习 5 6 3.1 案例-老师和学生 7 */ 8 9 public class PersonDemo { 10 public static void main(String[] args) { 11 Teacher t1 = new Teacher(); 12 t1.setName("tom"); 13 t1.setAge(30); 14 System.out.println(t1.getName() + "," + t1.getAge()); 15 t1.teach(); 16 17 Teacher t2 = new Teacher("amy", 28); 18 System.out.println(t2.getName() + "," + t2.getAge()); 19 t2.teach(); 20 21 Student s1 = new Student(); 22 s1.setName("zhangsan"); 23 s1.setAge(16); 24 System.out.println(s1.getName() + "," + s1.getAge()); 25 s1.study(); 26 27 Student s2 = new Student("lisi", 17); 28 System.out.println(s2.getName() + "," + s2.getAge()); 29 s2.study(); 30 } 31 }
1 package day1.yppah03; 2 3 public class Person { 4 5 private String name; 6 private int age; 7 8 public Person() { 9 } 10 11 public Person(String name, int age) { 12 this.name = name; 13 this.age = age; 14 } 15 16 public void setName(String name) { 17 this.name = name; 18 } 19 20 public void setAge(int age) { 21 this.age = age; 22 } 23 24 public String getName() { 25 return name; 26 } 27 28 public int getAge() { 29 return age; 30 } 31 32 }
1 package day1.yppah03; 2 3 public class Student extends Person{ 4 5 public Student() { 6 } 7 8 public Student(String name, int age) { 9 super(name, age); 10 } 11 12 public void study(){ 13 System.out.println("好好学习"); 14 } 15 16 }
1 package day1.yppah03; 2 3 public class Teacher extends Person{ 4 5 public Teacher(){} 6 7 public Teacher(String name, int age){ 8 /*this.name = name; //error 子类不可访问父类的私有成员 9 this.age = age;*/ 10 super(name, age); //利用父类有参构造实现子类的有参构造 11 } 12 13 public void teach(){ 14 System.out.println("好好教书"); 15 } 16 17 }