• Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating various objects from one class  RSS feed

 
Stephen Bell
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greetings all :-)

I have a question regarding basic object creation and would be grateful for any guidance.

Let's say I have a class 'Vehicle' and from this class, I want to create 3 objects.

So, I might have:


Now, lets also say, that each 'vehicle' has a variable that is only useful for a particular Vehicle type. For example:

The car object needs:

The plane object needs:

And the bicycle object needs:

I could create 3 new classes that all extend from the Vehicle class.

So I could then do something like:


Where the classes Car, Plane & Bicycle, all extend the class Vehicle.

All of my specific variables could then of course go into their respective classes.

Is it excessive to create child classes simply to hold a few or boolean/ints?

What are the other options?

I could just put all three variables into the Vehicle class, but each object would have 2 unused and irrelevant variables (more, if I had to create more vehicles with specific and unique properties).

So is the first option the 'correct' way to do this or am I missing something!?

Thanks!
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37496
546
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, the first example is the correct way to do this. iN larger programs, you tend to have more variables in the subclasses. But it's ok even if you don't.

Putting irrelevant instance variables is bad. It just invites you to mess it up later. And it makes the code harder to read.
 
Knute Snortum
Sheriff
Posts: 4281
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it excessive to create child classes simply to hold a few or boolean/ints?

Not at all. I'd create a subclass (don't say child class) for just one boolean. Vehicle could be an abstract class or an interface.
 
Campbell Ritchie
Marshal
Posts: 56553
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Surely it is
 
Stephen Bell
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the replies all, much appreciated!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!