Person类,Student类和Teacher类继承Person类。
他们有自己的say方法。本节我们会将不同的引用放到同一个Person数组里。动态调用不同的say方法。
1. Person类
package org.example.poly_.ployarr_;
import java.util.Objects;
/**
*@author 大力pig
*/
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
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;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public String say(){
return name+ "\t" + age;
}
}
2. Student类
package org.example.poly_.ployarr_;
import java.util.Objects;
/**
*@author 大力pig
*/
public class Student extends Person{
private double score;
public Student(String name, int age, double score) {
super(name, age);
this.score = score;
}
public Student(double score) {
this.score = score;
}
public Student() {
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
Student student = (Student) o;
return Double.compare(student.score, score) == 0;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), score);
}
//重写父类的say方法
@Override
public String say() {
return "Student: "+super.say() + " Score = " +score;
}
}
3. Teacher类
package org.example.poly_.ployarr_;
/**
* @author 大力pig
*/
public class Teacher extends Person {
private 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;
}
//重写父类的say方法
@Override
public String say() {
return "Teacher: " + super.say() + " Salary = " + salary;
}
}
4. Main测试类
public static void main(String[] args) {
//两个student, 两个teacher,都放在数组中,并且调用say方法。
Person[] persons = new Person[5];
persons[0] = new Person("jack", 20);
persons[1] = new Student("jackie", 18, 100);
persons[2] = new Student("smith", 19, 30.1);
persons[3] = new Teacher("scott", 30, 20000);
persons[4] = new Teacher("king", 50, 25000);
for (Person person : persons) {
System.out.println(person.say());
}
}
这样我们就动态的调用了多态数组的say方法。