Do I really have a car in my garage? [duplicate]

I’m a newbie to Java programming, trying to get the hang of OOP.

So I built this abstract class:

public abstract class Vehicle{....}

and 2 subclasses:

public class Car extends Vehicle{....}
public class Boat extends Vehicle{....}

Car and Boat also hold some unique fields and methods that aren’t common (don’t have the same name, so I can’t define an abstract method for them in Vehicle).

Now in mainClass I have setup my new Garage:

Vehicle[] myGarage= new Vehicle[10];
myGarage[0]=new Car(2,true);
myGarage[1]=new Boat(4,600);

I was very happy with polymorphism until I tried to access one of the fields that are unique to Car, such as:

boolean carIsAutomatic = myGarage[0].auto;

The compiler doesn’t accept that. I worked around this issue using casting:

boolean carIsAutomatic = ((Car)myGarage[0]).auto;

That works… but it doesn’t help with methods, just fields. Meaning I can’t do

(Car)myGarage[0].doSomeCarStuff();

So my question is – what do I really have in my garage? I’m trying to get the intuition as well as understand what’s going on “behind the scenes”.


for the sake of future readers, a short summary of the answers below:

  1. Yes, there’s a Car in myGarage[]
  2. Being a static typed language, the Java compiler will not lend access to methods/fields that are non-“Vehicle”, if accessing those through a data structure based on the Vehicle super class( such as Vehicle myGarage[])
  3. As for how to solve, there are 2 main approaches below:
    1. Use type casting, which will ease the compiler’s concerns and leave any errors in the design to run time
    2. The fact that I need casting says the design is flawed. If I need access to non-Vehicle capabilities then I shouldn’t be storing the Cars and Boats in a Vehicle based data structure. Either make all those capabilities belong to Vehicle, or use more specific (derived) type based structures
  4. In many cases, composition and/or interfaces would be a better alternative to inheritance. Probably the subject of my next question…
  5. Plus many other good insights down there, if one does have the time to browse through the answers.

13 Answers
13

Leave a Comment