Reputation: 185
So say I have 3 classes, Tester, Fruit (superclass), and Apple (subclass)
I have written a new method in Apple (which extends Fruit). The method being:
public String getAppleColor()
Now say in Tester I have created an array of 10 Fruit
Fruit fruitArray = new Fruit[10]
and say I make one of them
fruitArray[3] = new Apple()
This is fine, since Apple is also of type Fruit. However I wish to use my getAppleColor() on this specific element of the array:
String appleColor = fruitArray[3].getAppleColor();
How come this is not working? When I look at useable methods on fruitArray[3] in eclipse, none of my Apple methods show up, but I made fruitArray[3] an Apple?
Upvotes: 0
Views: 145
Reputation: 187
You'd better declare a method getColor()
in class Fruit
, override it in subclass Apple
, then you can get color of apple by fruitArray[3].getColor()
.
Upvotes: 1
Reputation: 361
You have to cast it to an Apple
since the compiler won't know that fruitArray[3]
will contain an Apple (it might contain any other sort of Fruit
). Try:
String appleColor = ((Apple)fruitArray[3]).getAppleColor();
Upvotes: 2
Reputation: 279880
The compiler cannot know that at runtime, an element declared as a Fruit
is actually an Apple
. As such, it won't let you call any methods declared in Apple
.
Your array is
Fruit[] fruitArray;
The compiler can only know that the elements in the array are Fruit
instances, nothing more.
Upvotes: 1
Reputation: 240860
You can't call getAppleColor()
on Fruit
reference, it doesn't declare that method
better design would be have getFruitColor()
defined and make Fruit
abstract class / make it interface and force each Fruit
implement this method
Compiler doesn't know what implementation it is going to be assigned at runtime
Upvotes: 2