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

前端之家收集整理的这篇文章主要介绍了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();
  }

猜你在找的Java相关文章