这段代码的最后两行说明了这个问题:当我使用对对象的引用时编译器工作,但当我将引用分配给数组元素时编译器工作。其余代码位于不同文件的同一包中。BioStudent 和 ChemStudent 和 Student 是不同的类。
package pkgPoly;
public class Poly {
public static void main(String[] arg) {
Student[] stud = new Student[3];
// create a biology student
BioStudent s1 = new BioStudent("Tom");
// create a chemistry student
ChemStudent s2 = new ChemStudent("Dick");
// fill the student body with studs
stud[0] = s1;
stud[1] = s2;
// compiler complains that it can't find symbol getMajor on next line
System.out.println("major: " + stud[0].getMajor() ); // doesn't compile;
System.out.println("major: " + s0.getMajor() ); // works: compiles and runs correctly
}
}