public class Person {
private String name;
private int age;
```java
public Person(String name, int age) {
this.setName(name);
this.setAge(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 "我叫"+getName()+",今年"+getAge()+"岁了";
}
public void putong(){
System.out.println("我是一个普通人");
}
}
public class Student extends Person{
private double grade;
public Student(String name,int age,double grade) {
super(name, age);
this.setGrade(grade);
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
public String say(){
return "我叫"+getName()+",今年"+getAge()+"岁了,"+"分数"+getGrade();
}
public void study(){
System.out.println("我正在学习");
}
}
public class Teacher extends Person{
private double salary;
public Teacher(String name,int age,double salary) {
super(name,age);
this.setSalary(salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String say(){
return "我叫"+getName()+",今年"+getAge()+"岁了,"+"薪水"+getSalary();
}
public void teach(){
System.out.println("我正在教学");
}
}
import java.util.Arrays;
public class master {
public static void main(String[]args){
Person[] persons=new Person[3];
persons[0]=new Person("小明",16);
persons[1]=new Student("小米",18,100);
persons[2]=new Teacher("史塔克",50,12000);
// System.out.println(Arrays.toString(persons));
for (int i=0;i< persons.length;i++){
System.out.println(persons[i].say());
if (persons[i] instanceof Person){
Person person=(Person) persons[i];
person.putong();
}else if (persons[i] instanceof Student){
Student student=(Student) persons[i];
student.study();
}else if (persons[i] instanceof Teacher){
Teacher teacher=(Teacher) persons[i];
teacher.teach();
}
else {
System.out.println("对象不存在");
}
}
}
}