Polymorphic behavior not being implemented

Posted by Garrett A. Hughes on Stack Overflow See other posts from Stack Overflow or by Garrett A. Hughes
Published on 2013-10-28T21:43:43Z Indexed on 2013/10/28 21:53 UTC
Read the original article Hit count: 156

Filed under:

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
     }
}

© Stack Overflow or respective owner

Related posts about java