案例:老师和学生
需求:定义老师类和学生类,然后写代码测试;最后找到老师类和学生类当中的共性内容,抽取出一个父类,
用继承的方式改写代码,并进行测试
思路:
定义老师类(姓名,年龄,教书 ( ) )
定义学生类(姓名,年龄,学习( ))
定义测试类,写代码测试
Person类:
package com.ithmm_05; public class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
老师类继承Person:
package com.ithmm_05; public class Teacher extends Person { public Teacher(){ } public Teacher(String name,int age){ // this.name = name; // this.age = age; super(name, age); } public void teach() { System.out.println("用爱育人,助力学生完成梦想"); } }
学生类extendsPerson类:
package com.ithmm_05; public class Student extends Person{ public Student(){ } public Student(String nmae,int age){ } public void learn(){ System.out.println("好好学习,天天向上"); } }
测试类:
public class PersonDemo { public static void main(String[] args) { Teacher t1 =new Teacher(); t1.setName("hmm"); t1.setAge(20); System.out.println(t1.getName()+","+t1.getAge()); t1.teach(); Teacher t2 =new Teacher("yyy",25); System.out.println(t2.getName()+","+t2.getAge()); t2.teach(); System.out.println("----------------------------------------------"); Student s1 =new Student(); s1.setName("lwx"); s1.setAge(17); System.out.println(s1.getName()+","+s1.getAge()); s1.learn(); } }