Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: inheritance and arrays, and their children

Java: Simple question... why can I not use array[0].childMethod?

Notice that myList.method() works, but when stored in an array, method() becomes unusable.

Any help is appreciated.

public class Main {
    public static void main(String[] args) {
        Vehicle[] array = new Vehicle[1];

        Car myList = new Car();
        System.out.println( myList.myMethod() );    //Output: 1

        array[0] = myList;
        System.out.println( array[0].myMethod() );  //Doesn't work.

    }
}
class Vehicle{

}
class Car extends Vehicle{
    public int myMethod(){
        return 1;
    }
}
like image 935
nana413413 Avatar asked Dec 19 '22 08:12

nana413413


1 Answers

Notice Vehicle is your PARENT Class

 Vehicle[] array = new Vehicle[1];//instance of parent

Car is your inherited CHILD class

 Car myList = new Car();//instance of child

Child can access Parent's methods and its own methods but not Vice versa. Parent can't access child's method unless you implement Dynamic Method Dispatch/Runtime Polymorphism . (This is termed as Polymorphism in biology - one of the OOP pillars)

Your array is instance of parent so it can't access myMethod of child. But myList is instance of car so it can access method myMethod

For that you will have to declare as

 Car[] array = new Car[1];

Or else you can simply cast like

 ((Car)array[0]).myMethod()
like image 55
minigeek Avatar answered Dec 29 '22 01:12

minigeek