【发布时间】:2019-03-09 15:58:09
【问题描述】:
我有 2 个类 - “学生”和“员工”,它们都扩展了 Person 类。 所有 3 个类中都有方法。 在我的演示类中,我必须从每个类(学生、员工和人员)创建 2 个对象,并将它们放入人员类型的数组中。然后我必须遍历数组,根据对象是来自 Student、Employee 还是 Person,我必须在这个类/子类中调用一个方法。问题是一旦这些对象进入 Person 数组,只有 Person 类中的 .methods 是可见的。如果我的 array[i]."method" 来自 Student 或 Employee (array[i].showStudentInfo() 和 array[i].showEmplyeeInfo()),我怎样才能找到它 提前谢谢!
public class Person {
String name;
int age;
boolean isMan;
Person(String name, int age, boolean isMan) {
this.name = name;
this.age = age;
this.isMan = isMan;
}
void showPersonInfo() {
System.out.println("Име: " + this.name + " | " + "години: " + this.age + " | " + "мъж ли е: " + this.isMan);
}
}
public class Student extends Person {
double score;
Student(String name, int age, boolean isMan, double score) {
super(name, age, isMan);
this.score = score;
}
public void showStudentInfo() {
System.out.println("Име: " + super.name + " | " + "години: " + super.age + " | " + "мъж ли е: " + " | "
+ super.isMan + " | " + "Оценка: " + this.score);
}
}
public class Employee extends Person {
double daySallary;
double extraSum;
Employee(String name, int age, boolean isMan, double daySallary){
super(name, age, isMan);
this.daySallary=daySallary;
}
double calculateOvertime(double hours) {
if (this.age< 18)
extraSum = 0;
else
extraSum = (this.daySallary / 8) * hours * 1.5;
return extraSum;
}
public void showEmployeeInfo() {
System.out.println("Име: " + super.name + " | " + "години: " + super.age + " | " + "мъж ли е: " + " | "
+ super.isMan + " | " + "Допълнителна сума от оставане след работно време: " + this.extraSum);
}
}
public class Demo {
public static void main(String[] args) {
Person ivan = new Person("Ivan Georgiev", 27, true);
Person nikola = new Person("Nikola Ivanov", 30, true);
Student iskra = new Student("Iskra Dimitrova", 21, false, 4.5);
Student georgi = new Student("Georgi Kazakov", 19, true, 5.5);
Employee neli = new Employee("Anelia Stoicheva", 35, false, 50);
Employee monika = new Employee("Monika Petrova", 42, false, 80);
Person[] array = new Person[10];
array[0] = ivan;
array[1] = nikola;
array[2] = iskra;
array[3] = georgi;
array[4] = neli;
array[5] = monika;
for (int i = 0; i < 6; i++) {
if (array[i].getClass().equals(ivan.getClass())) {
array[i].showPersonInfo();
}
if (array[i].getClass().equals(iskra.getClass())) {
array[i].showStudentInfo();
}
if (array[i].getClass().equals(neli.getClass())) {
array[i].showEmployeeInfo();
}
}
【问题讨论】:
-
如果您知道您正在使用的
Person的类型,您可以将对象转换为正确的类型:((Student) array[i]).showStudentInfo() -
你的设计可能会更好,但是,如果你有
Person声明一个简单的showInfo()方法并在子类中覆盖它。 -
使用
instanceOf或者从 OOP 的角度更好地添加和抽象showInfo方法到超类并在数组的每个元素上调用它。
标签: java