java – 一个ArrayList中的多个对象类型

我有一个名为User的抽象类,用户可以创建为学生类型或教师类型.我已经创建了一个用户(学生和教师)的ArrayList,我想要做的是调用一个方法示例,具体取决于当前对象是什么的实例:
for (User user : listofUsers) {

  String name = user.getName();

  if (user instanceof Student) {

    // call getGrade();

  } else { // it is an instance of a Teacher

    // call getSubject();
  }
}

我遇到的问题是因为它是User对象的ArrayList,它无法获取Student类型方法,例如getGrade().但是,因为我能够确定当前用户的实例是什么,所以我很好奇是否仍然可以根据用户的类型调用特定方法.

这是可能的,还是我必须将用户类型分成单独的列表?

请尽快回复,非常感谢.

解决方法

检查 downcast

In object-oriented programming,downcasting or type refinement is the
act of casting a reference of a base class to one of its derived
classes.

In many programming languages,it is possible to check through type
introspection to determine whether the type of the referenced object
is indeed the one being cast to or a derived type of it,and thus
issue an error if it is not the case.

In other words,when a variable of the base class (parent class) has a
value of the derived class (child class),downcasting is possible.

将您的代码更改为:

if (user instanceof Student) {

    ((Student) user).getGrade();

  } else { // it is an instance of a Teacher

    ((Teacher) user).getSubject();
  }

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...