[Java] 纯文本查看 复制代码
class Test4_Person {
public static void main(String[] args) {
Student s = new Student();
s.setName("张三");
s.setAge(23);
System.out.println(s.getName() + "............" + s.getAge());
s.eat();
s.study();
System.out.println("-------------------------------------------------------------");
Teacher t = new Teacher("李四", 24);
System.out.println(t.getName() + "............" + t.getAge());
t.eat();
t.teach();
}
}
class Person {
String name = "王五"; //姓名
int age; //年龄
//age = 88; //为啥不可以?
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("吃饭");
}
}
class Student extends Person{
public Student() {} //空参构造
public Student(String name, int age) { //有参构造
super(name, age);
}
public void eat(){ //学生吃饭
System.out.println(this.getName() + "学生吃饭");
}
public void study(){ //学生学习
System.out.println(getName() + "学生学习");
}
}
class Teacher extends Person{
public Teacher() {} //空参构造
public Teacher(String name, int age) { //有参构造
super(name, age);
}
public void eat(){ //学生吃饭
System.out.println(super.getName() + "老师讲课");//为啥不是王五老师讲课?如果都和this一样用,那还要this干嘛?
}
public void teach(){ //老师讲课
System.out.println(this.getName() + "老师讲课");
}
}