微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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();
  }

原文地址:https://www.jb51.cc/java/121070.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐