加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:50:52 所属栏目:Java 来源:网络整理
导读:我有一个名为User的抽象类,用户可以创建为学生类型或教师类型.我已经创建了一个用户(学生和教师)的ArrayList,我想要做的是调用一个方法示例,具体取决于当前对象是什么的实例: for (User user : listOfUsers) { String name = user.getName(); if (user inst
我有一个名为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();
  }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读