【发布时间】:2018-11-26 20:09:12
【问题描述】:
我有一个我正在尝试完成的作业,但到目前为止我无法找到解决方案,我的问题是:
我有一个由 Student 和 Employee 类扩展的超类 Person。 Person 有字段名称、年龄、男性,然后 Student 有分数,Employee 有薪水。 对于所有类,我都有打印对象信息的方法。 人物示例:
void showPersonInfo() {
System.out.println( this.getClass().getSimpleName() + " name: " + this.name);
System.out.println( this.getClass().getSimpleName() +" age : " + this.age);
System.out.println(isMale ? this.getClass().getSimpleName() + " is male" : this.getClass().getSimpleName() + " is female");
}
对于员工(学生也一样):
void showEmployeeInfo(){
super.showPersonInfo();
System.out.println(this.getClass().getSimpleName() + " salary per day is: " + this.daySalary);
}
然后我有一个主要方法,我必须制作一个包含 10 个人的数组,并用学生、个人和员工填充它。 迭代之后,我必须相应地调用子类的方法 - 员工的 showEmployeeInfo 等。我想你明白了。
到目前为止,我已经这样做了:
for(int index = 0; index < guys.length; index++) {
if(guys[index].getClass() == Person.class) {
guys[index].showPersonInfo();
System.out.println();
}
我试图对其他类做同样的事情,我设法用 getClass() 找到它们,但我不能调用子类方法。这甚至可能吗?到目前为止我尝试了一些东西,但没有任何效果。有什么想法吗?
P.S:我认为我可以将所有方法设为静态,但我认为这不应该是解决方案。 :)
【问题讨论】:
-
guys定义为什么?如果是Person[],那么你可以做类似if (guys[index] instanceof Employee) { ((Employee)guys[index]).showEmployeeInfo(); } -
效果很好!非常感谢,到目前为止我们还没有学会“instanceof”的使用,但这是一个开始的好时机!再次感谢!
标签: java oop inheritance subclass superclass