简体   繁体   English

一个ArrayList中的多个对象类型

[英]Multiple object types in one ArrayList

I have an abstract class called User, a user can be created either as a Student type or as a Teacher type. 我有一个名为User的抽象类,用户可以创建为学生类型或教师类型。 I have made an ArrayList of users (of students and teachers) and what I am trying to do is call a method example depending on what the current object is an instance of: 我已经创建了一个用户(学生和教师)的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();
  }
}

The problem I'm having is because it is an ArrayList of User objects, it can't get the Student type method, for example, getGrade(). 我遇到的问题是因为它是User对象的ArrayList,它无法获取Student类型方法,例如getGrade()。 However, because I am able to determine what the current user is an instance of, I'm curious as to whether or not it is still possible to call a specific method depending on what type of user it is. 但是,因为我能够确定当前用户的实例是什么,所以我很好奇是否仍然可以根据用户的类型调用特定方法。

Is this possible, or do I have to separate the user types into separate lists? 这是可能的,还是我必须将用户类型分成单独的列表?

Please reply soon, many thanks. 请尽快回复,非常感谢。

You'll need to cast them to the class before using the method. 在使用该方法之前,您需要将它们强制转换为类。

for (User user : listOfUsers) {

    String name = user.getName();

    if (user instanceof Student) {

        Student tmp = (Student)user;

        // call getGrade();
        tmp.getGrade();

    } else { // it is an instance of a Teacher
        Teacher tmp = (Teacher)user;
        // call getSubject();
        tmp.getSubject();
    }
}

Check the 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. 换句话说,当基类(父类)的变量具有派生类(子类)的值时,可以进行向下转换。

Change your code to: 将您的代码更改为:

if (user instanceof Student) {

    ((Student) user).getGrade();

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

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

Store student and teacher objects in userList and then depending on the instanceOf condition call the respective class method by typeCasting to UserType 将student和teacher对象存储在userList中,然后根据instanceOf条件通过typeCasting调用相应的类方法到UserType

Consider below sample code 请考虑以下示例代码

   abstract class User{

        public abstract String getName();
    }

    class Student extends User{

        @Override
        public String getName() {
            // TODO Auto-generated method stub
            return "Student";
        }

        public String getGrade(){
            return "First Class";
        }

    }


    class Teacher extends User{

        @Override
        public String getName() {
            // TODO Auto-generated method stub
            return "Teacher";
        }

        public String getSubject(){
            return "Java";
        }

    }

public class  Util {

public static void main(String[] args) {


        Student s = new Student();
        Teacher t = new Teacher();

        ArrayList<User> list = new ArrayList<User>();
        list.add(s);
        list.add(t);

        for(User user :list){
            if(user instanceof Student){
                System.out.println(((Student) user).getGrade());
            }

            if(user instanceof Teacher){
                System.out.println(((Teacher) user).getSubject());
            }
        }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM