Polymorphic behavior not being implemented
- by Garrett A. Hughes
The last two lines of this code illustrate the problem: the compiler works when I use the reference to the object, but not when I assign the reference to an array element. The rest of the code is in the same package in separate files. BioStudent and ChemStudent are separate classes, as well as 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] = s0;
stud[1] = s1;
// 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
}
}