2013-10-28 45 views
0

该代码的最后两行示出了该问题:当我使用参考对象编译器的工作原理,但不是当我分配参照的数组元素。其余代码位于单独文件的相同包中。 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 
    } 
} 
+0

你能发布错误信息吗?可能还有'Student'的代码。 – iamnotmaynard

+0

编译器抱怨说在下一行找不到符号getMajor - 他在注释 – Raffaele

+0

中写道错误消息是“source \ pkgPoly \ Poly.java:50:错误:找不到符号符号:method getMajor()location:class学生 –

回答

1

有很多缺失的信息,比如什么是S0,或者如果BioStudent和ChemStudent延长学生,但是我只是假设这一切是真实的,S0或者是BioStudent或ChemStudent的。

如果是这样,我不完全确定正确的术语,但是当您使用父类型的引用变量并将其指向一个Child对象时,如果这些方法覆盖父方法,则只能访问子方法。

换句话说,你需要在你的父类的学生,那么在你的子类BioStudent和/或ChemStudent重写定义的getMajor()方法。

+0

我错过了Student类中的getMajor()方法 - 谢谢克里斯托瓦尔! –

+0

我喜欢这个网站! –

1

根根类学生的对象。

我假设一些东西 -

  • BioStudent和ChemStudent扩展Student类。
  • BioStudent有一个方法getMajor()
  • 学生类没有!

这就是stud [0] .getMajor()给你一个编译时错误的原因。

你必须把它强制转换为学生的子类。

System.out.println("major: " + ((BioStudent) stud[0]).getMajor()); 
+0

尽管最好在'Student'中定义'getMajor()',而不是在每次调用方法时必须转换为子类 - 哪个子类应该向哪个子类转换? – iamnotmaynard

+0

我错过了Student类中的getMajor()方法 - 谢谢ajc –

+0

如果在子类中重写方法,则不需要转换。我只是在玩这个东西,因为它对我来说都是新的 - 再次感谢 –

1

根据给出的信息我假设了几件事情。

  • 学生是一个超类
  • BioStudent和ChemStudent延伸学生
  • 螺柱[0] = S1
  • 螺柱[1] = S2

您得到的错误是因为学生类没有getMajor(),但生物学员和化学学生有这种方法。

您已经创建了一个学生数组。对于编译器stud[0]是学生类,而不是生物学员或ChemStudent。只有在运行时,jre才会知道stud [0]具有BioStudent并且stud [1]具有ChemStudent。这就是为什么你得到编译错误。

  • 解决方案1:

    要么添加getMajor()方法Student类和其他2类重写它。

OR

  • 解决方案2:

    加给你的打印语句(BioStudent stud[0]).getMajor()类型转换 - 这明确地表明这是BioStudent对象,编译器会知道BioStudent有getMajor()