我有一个作业想要完成,但到目前为止我找不到解决方案,我的问题是这样的:
我有一个父类(super class)人员,它由学生类和雇员类扩展。 人员有姓名、年龄、男性字段,然后学生有分数,员工有工资。 对于所有类,我都有打印对象信息的方法。 人的示例:
无效 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 Employee 等。我想你明白了。
到目前为止我已经这样做了:
for(int index = 0; index < guys.length; index++) {
if(guys[index].getClass() == Person.class) {
guys[index].showPersonInfo();
System.out.println();
}
我正在尝试对其他类执行相同的操作,并且我设法使用 getClass() 找到它们,但我无法调用子类方法。这可能吗?到目前为止我尝试了一些东西但没有任何效果..有什么想法吗?
P.S:我认为我可以将所有方法设为静态,但我认为这不应该是解决方案。 :)
最佳答案
免责声明:这不一定是您的老师/讲师期望的答案。
<小时/>您可以将 showXXXInfo
方法的名称更改为 showInfo
,并让子类中的方法覆盖父类(super class)中的方法:
// in Person
void showInfo() {
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");
}
// in Employee
@Override
void showInfo(){
super.showInfo();
System.out.println(this.getClass().getSimpleName() + " salary per day is: " + this.daySalary);
}
现在您只需对数组的每个元素调用 showInfo
即可,根据类型,将自动调用正确的方法。
关于java - 父类(super class)实例数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53488296/