/*练习: 创建若干个Student或者Employee对象,存储起来。 循环遍历每个成员,调用其eat方法 如果是员工就调用working 如果是学生就调用学习方法*/
类
Person
package com.atguigu.test;
public class Person {
public int id;
public String name="父亲";
public Person(){
super();
}
public void eat(){
System.out.println("吃饭");
}
public void run(){
System.out.println("奔跑");
}
}
Student
package com.atguigu.test;
public class Student extends Person{
public double score;
@Override
public void eat() {
System.out.println("吃食堂");
}
public void study(){
System.out.println("在学习");
}
}
Employee
package com.atguigu.test;
public class Employee extends Person{
public double salary=2000;
public String name="打工人";
@Override
public void eat() {
System.out.println(name+"吃员工餐"+salary);
}
public void working(){
System.out.println("打工人在工作");
}
}
测试类
package com.atguigu.test;
/*练习:
创建若干个Student或者Employee对象,存储起来。
循环遍历每个成员,调用其eat方法
如果是员工就调用working
如果是学生就调用学习方法*/
public class Test1 {
public static void main(String[] args) {
Person[] persons = new Person[3];
persons[0] = new Employee();
persons[1] = new Student();
persons[2] = new Employee();
for (int i = 0; i < persons.length; i++) {
persons[i].eat();
if(persons[i] instanceof Employee){
Employee employee = (Employee) persons[i];
employee.working();
}else if(persons[i] instanceof Student){
Student student = (Student) persons[i];
student.study();
}
}
}
}