需求:定义老师类和学生类,然后写代码测试,最后找到老师类和学生类当中的共性内容,抽取出一个父类,用继承的方式改写代码,并进行测试
思路:
1.定义老师类(姓名,年龄,教书())
2.定义学生类(姓名,年龄,学习())
3.定义测试类,写代码测试
4.共性抽取父类,定义人类(姓名,年龄)
5.定义老师类,继承人类,并给出自己特有方法:教书()
6.定义学生类,继承人类,并给出自己特有方法: 学习()
7.定义测试类,写出代码测试
package com.ithema_27;
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;
}
}
package com.ithema_27;
public class Student extends Person{
public Student(){
}
public Student(String name,int age){
// = name;
// this.age = age;
super(name,age);
}
public void student(){
System.out.println("好好学习,天天向上");
}
}
package com.ithema_27;
public class Teacher extends Person{
public Teacher(){
}
public Teacher(String name,int age){
// = name;
// this.age = age;
super(name,age);
}
public void teach(){
System.out.println("用爱成就每一位学员");
}
}
package com.ithema_27;
/*
测试类
*/
public class Demo {
public static void main(String[] args) {
//创建老师类对象并进行测试
Teacher t1 = new Teacher();
t1.setName("林青霞");
t1.setAge(30);
System.out.println(t1.getName() + "," + t1.getAge());
t1.teach();
Teacher t2 = new Teacher("风清扬", 33);
System.out.println(t2.getName() + "," + t2.getAge());
t2.teach();
//创建学生类对象并进行测试
Student s1 = new Student();
s1.setName("王昱翔");
s1.setAge(35);
System.out.println(s1.getName() + "," + s1.getAge());
s1.student();
Student s2 = new Student("王新权",35);
System.out.println(s2.getName() + "," + s2.getAge());
s2.student();
}