-2

I have a class Person and a class Instructor that extends Person

public class Driver {
public static void main(String args[]) {
    Person[] array = new Person[5];
    array[1] = new Person("John Doe");
    array[2] = new Person("Bobby Gram");
    array[3] = new Person("Jeb Too");
    array[4] = new Instructor("Jill Crill", "Computer Science");
    array[5] = new Instructor("Hello World", "Math");

    for(int i = 0; i < array.length; i++) {
        System.out.println(array[i].toString());
    }
    for(int i = 0; i < array.length; i++) {
        int total = 0;
        if (array[i] instanceof Instructor) {
            Person person = (Instructor) array[i];
            person.getSubject();
        }
    }

}
}

    for(int i = 0; i < array.length; i++) {
        int total = 0;
        if (array[i] instanceof Instructor) {
            Person person = (Instructor) array[i];
            person.getSubject();    //error: The method getSubject() is undefined for the type Person
        }
    }

It's giving me an error even though I downcasted? The Instructor class has a getSubject() method.

  • what is the error that are you receiving? can you add it to your question? thanks – Leviand Jul 25 '18 at 08:25
  • 3
    It makes little sense to cast to `Instructor` when you assign it to a `Person` type variable right after that. Did you mean `Instructor person = (Instructor) array[i];` by any chance? – OH GOD SPIDERS Jul 25 '18 at 08:25

1 Answers1

0
if (array[i] instanceof Instructor) {
        Instructor person = (Instructor) array[i];
        person.getSubject();
}

Since person is reference variable for Person class it is not able to identify teh getSubject() method even though the dynamically created object is instance of Instructor. Change the code as per the above mentioned lines which will fix your problem.

Mohan Raj
  • 23
  • 4