访问 Object[] 数组成员的方法

Accessing the methods of a member of an Object[] array

我必须创建一个对象数组然后随机填充。在这个数组中,我需要随机放置 100 个,Person(base)Student(sub),Professor(sub),Course(学生加教授的数组)和一个 Circle(无关)。我还必须命名并计算我输入数组的每个人(包括教授和学生)。

    Object[] array = new Object[100];
    String[] names = new String[]{"Ben","Anne","Joe","Sue","John","Betty","Robert","Mary",
                                  "Mark","Jane","Paul","Willow","Alex","Courtney","Jack",
                                  "Rachel"};
    int count = 0;
    for(int i=0; i<100; i++){
       int a = (int)(Math.random()*5);
       String n = names[(int)(Math.random()*16)];
       if(a == 0){array[i]= new Person(n); count++;}
       else if(a == 1){array[i]= new Student(n); count++;}
       else if(a == 2){array[i]= new Professor(n); count++;}
       else if(a == 3){
           array[i]= new Course();
           count = count + 11;
           for(int j = 0; j<10; j++){
               String l = names[(int)(Math.random()*16)];
               array[i].getClasslist()[j].setName(l);}
       }
       else if(a == 4){array[i]= new Circle();}
    }

但是,每当我尝试调用其中一个成员的方法时,它都会告诉我 "Cannot find Symbol- Method getClasslist()" 或 setName 或我要调用的任何内容。知道如何解决这个问题吗?

就您的实际代码而言,您需要按照您编写代码的方式显式转换 array[i]

for(int j = 0; j<10; j++){
   String l = names[(int)(Math.random()*16)];
   ((Course) array[i]).getClasslist()[j].setName(l);
}

...尽管在一个数组中混合许多没有公共接口的不同类型的整个事情是一个巨大的代码味道。

当你有一系列混合对象时,你必须先检查对象的实际类型,然后才能调用特定于类型的方法。为此,请使用 instanceof:

for (Object obj : array) {
    if (obj instanceof Person) { // includes subclasses Student and Professor
        Person person = (Person)obj;
        // now you can call Person methods
    } else if (obj instanceof Course) {
        Course course = (Course)obj;
        for (Object member : course.getMembers()) {
            if (member instanceof Person) {
                Person person = (Person)member;
                // now you can call Person methods
            }
        }
    }
}

我认为将所有这些不同的 类 放在一个 Object[] 中是完全可以的,只要在程序的后面部分数组的所有元素仅用作对象(好吧,Object 不是一个花哨的界面——但这只是一个练习)。

但最好先初始化整个 Course 对象,然后才将其放入数组中:

   else if(a == 3){
       Course course = new Course();
       count = count + 11;
       for(int j = 0; j<10; j++){
           String l = names[(int)(Math.random()*16)];
           course.getClasslist()[j].setName(l);//no casting needed
       }
       array[i]=course;//we can forget the real type of the object now
   }