例如如下代码:
class Demo {
public static void main(String [] args) {
Student s = new Student();
s.setName("张三");
s.setAge(23);
s.eat();
s.study();
Teacher t = new Teacher("李四",24);
t.eat();
t.teach();
}
}
class Person {
private String name;
private int age;
public Person() {}
public Person(String name,int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void eat() {
System.out.println(name+"吃饭");
}
}
class Student extends Person {
public Student() {}
public Student(String name,int age) {
super(name,age);
}
public void study() {
System.out.println(getName()+"学习");
}
}
class Teacher extends Person {
public Teacher() {}
public Teacher(String name,int age) {
super(name,age);
}
public void teach() {
System.out.println(getName()+"讲课");
}
}
|
|