创建四个类:Person类、Student类、Teacher类和Test类
Student类、Teacher类继承Person类
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String say(){
return "名字为:"+name+", 年龄为:"+age;
}
}
public class Student extends Person{
double score;
public Student(String name, int age, double score) {
super(name, age);
this.score = score;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String say(){
return "学生"+super.say()+", 成绩为"+score;
}
//学生私有方法
public void study(){
System.out.println("学生"+getName()+"正在学习Java~");
}
}
public class Teacher extends Person{
double salary;
public Teacher(String name, int age, double salary) {
super(name, age);
this.salary = salary;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String say(){
return "老师"+super.say()+", 工资为"+salary;
}
public void teach(){
System.out.println("老师"+getName()+"正在教Java~");
}
}
public class Test {
public static void main(String[] args) {
Person[] people=new Person[5];
people[0]=new Person("Tom",38);
people[1]=new Student("lxl",18,98);
people[2]=new Student("lky",21,78);
people[3]=new Teacher("Tm",32,5000);
people[4]=new Teacher("lll",48,2000);
for (int i = 0; i <people.length ; i++) {
System.out.println(people[i].say());
if (people[i] instanceof Student) {//判断是否为Student类,否则不能访问study方法
//如果不是,强制转换,向下转型
Student student = (Student) people[i];
student.study();
//也可以使用一条语句代替
// ((Student)people[i]).study();
} else if (people[i] instanceof Teacher) {//判断是否为Student类,否则不能访问study方法
//如果不是,强制转换,向下转型
Teacher teacher = (Teacher) people[i];
teacher.teach();
} else if (people[i] instanceof Person) {
}else {
System.out.println("你输入的类型有错误");
}
}
}
}