案例描述:
在班级中上课时,老师在讲台上讲课,偶有提问,会点名学生回答问题。虽然老师和学生都在讲话,但讲话的具体内容却不相同。本案例要求使用抽象类的知识编写一个程序实现老师上课的情景
运行结果:
代码如下:
创建抽象类:
/**
* 2022/3/20
*/
public abstract class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
abstract void dz();
abstract void xw();
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
学生类和老师类继承抽象类:
/**
* 2022/3/20
*/
public class Student extends Person {
public Student(String name, int age) {
super(name, age);
}
@Override
void dz() {
System.out.println(getName() + "同学在听老师讲课!");
}
@Override
void xw() {
System.out.println("大家好,我叫" + getName() + "今年" + getAge() + "岁了,爱好是学习!");
}
}
/**
* 2022/3/20
*/
public class Teacher extends Person{
Student s ;
public Teacher(String name, int age,Student s) {
super(name, age);
this.s = s;
}
@Override
void dz() {
System.out.println(getName() + "老师在给" +s.getName() +"同学讲课!");
}
@Override
void xw() {
System.out.println("请" + s.getName() + "同学做一下自我介绍!");
}
}
最后创建测试类:
/**
* 2022/3/20
*/
public class Demo {
public static void main(String[] args) {
Student s = new Student("小陈", 19);
Teacher t = new Teacher("张", 35,s);
t.dz();
s.dz();
System.out.println("------------------");
t.xw();
s.xw();
}
}