user4205912
user4205912

Reputation:

Can I access a subclass object's properties through a superclass reference in Java?

Let's say I have a class called Food and in the constructor it has attributes for price, # of calories, and a description.

I also have a subclass of Food called Burger, and the Burger has an additional attribute for type of meat.

Now if I create an array of Food instances that contains instances of the Burger class, can I access the type of meat attribute through the array?

Sorry if this is confusing, but I want to know if I can (and how) I can access parent and child properties in an array of parent and child objects. I am using Java too.

Upvotes: 4

Views: 2452

Answers (2)

Jim Garrison
Jim Garrison

Reputation: 86774

In your case, the subclass Burger's meat attribute is specific to that subclass, so the only option is to downcast the Food object to Burger, at the time you want to access its Burger-specific properties. This is fraught with problems if your collection (array) contains different subclasses, as the cast can fail.

Food[] foods = new Food[n];
Food[0] = new Burger(...);
Food[1] = new Vegetable(...);
Meat m1 = ((Burger)foods[0]).getMeat(); // This is OK
Meat m2 = ((Burger)foods[1]).getMeat(); // ClassCastException

Or better

for (Food f : foods)
{
    if (f instanceof Burger)
    {
        Meat m = ((Burger)foods[0]).getMeat(); 
        // other Burger-related processing
    }
    else if (f instanceof ...someothersubclass)
    {
         ...

This tends to be rather brittle, but you can't use polymorphism to streamline things here. Runtime (dynamic) dispatch works only for overridden methods. Overloaded methods in the same class are resolved at compile time.

Upvotes: 0

nhouser9
nhouser9

Reputation: 6780

You can access the properties of a Burger even if it is stored in an array of Food. First you will need to cast it to a Burger so your program knows what type it is. Since not all objects in your array of Food are Burgers, it is a good idea to check its type first. Something like this:

Food[] myFoods; //your food array
if (Burger.isInstance(myFoods[0])) { //check that the Food is a Burger
 ((Burger)myFoods[0]).meatType; //cast the object to a Burger and access its property
}

Upvotes: 1

Related Questions