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;
}
}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With