該代碼的最後兩行示出了該問題:當我使用參考對象編譯器的工作原理,但不是當我分配參照的數組元素。其餘代碼位於單獨文件的相同包中。 BioStudent和ChemStudent是獨立的班級,以及學生。多態行爲沒有得到執行
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
}
}
你能發佈錯誤信息嗎?可能還有'Student'的代碼。 – iamnotmaynard
編譯器抱怨說在下一行找不到符號getMajor - 他在註釋 – Raffaele
中寫道錯誤消息是「source \ pkgPoly \ Poly.java:50:錯誤:找不到符號符號:method getMajor()location:class學生 –