Java
定义一个抽象类 Person,有 name,age,sex 三个属性,创建构造函数,给这三个属性赋值,重写打印描述信息方法,打印三个属性值;这个类中有两个抽象方法 work 和 hello;定义两个子类 Teacher,Student;教师的 work 实现是:教书育人,hello 实现是:“同学好”;学生的 work 实现是:认真学习,hello 实现是“老师好”。
Person.java
public abstract class Person {
String name;
int age;
String sex;
public Person(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public String toString()
{
return "name:"+name+" age:"+age+" sex:"+sex;
}
abstract void work();
abstract void hello();
}
Teacher.java
public class Teacher extends Person
{
public Teacher(String name, int age, String sex)
{
super(name, age, sex);
}
public void work()
{
System.out.println("教书育人");
}
public void hello()
{
System.out.println("同学好");
}
}
Student.java
public class Student extends Person
{
public Student(String name, int age, String sex)
{
super(name, age, sex);
}
@Override
public void work() {
System.out.println("认真学习");
}
@Override
public void hello() {
System.out.println("老师好");
}
}
Test.java
public class Test {
public static void main(String[] args) {
Teacher Tom=new Teacher("Tom",24,"male");
Student Rachel=new Student("Rachel",20,"female");
Tom.work();
Tom.hello();
Rachel.work();
Rachel.hello();
}
}