0

I have class Fruit with data and logic.

Now I need a lot of different fruits, which only differ in: name, bitmap, and some other data.

Is there any sense in making a new subclass for each fruit? They have all "is a" relationship with fruit. But they don't add new behaviour or fields.

Maybe it's better just to give the fuit a "type" field, instead of subclassing it? Is anything wrong with that?

2 Answers 2

2

What kind of types of fruit are you trying to distinguish? If its just a typing diffidence I tend to use an enum value, from an enum list defined in the base class (in this case fruit) and then passed or initialized on the inheriting class's constructor.

eg

class Fruit { public: enum Type { SPIKEY, RED, ROUND, SQUISHY }; Fruit(Type type) { mType = type; } protected: Type mType; }; 

you can just define specific values in constructor for name etc

Sign up to request clarification or add additional context in comments.

1 Comment

This is like kasavbere's answer but with enum values. Same comment.
2

One class is sufficient, if I understand correctly. upon initialization, the name may be passed.

public class Fruit{ String name; ...//bit map, etc public Fruit(String name, ...){ this.name=name; ...//bit map } } 

user class:

 Fruit apple = new Fruit("apple", ...); 

1 Comment

Yes, the question is if there's something wrong with this approach, but I guess it's the right one. Otherwise I get 50+ classes just because of data and that doesn't make any sense.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.