Extending a class or adding a boolean parameter

When writing a program in Java, if I have a special case of an object that needs to be handled differently by the main class, but it does not require any additional methods, is it better to add a Boolean parameter to the constructor of an object such as isSpecial, and check Is the object special in the main class or for creating a new object that extends the original?

Example:

I have a Cat class. If a cat has whiskers, I want to print "This cat has whiskers!" in the main class.

Would it be better to have a WhiskerCat class or just add a boolean parameter to a Cat constructor such as hasWhiskers?

+4
source share
5 answers

Just add the boolean parameter. You do not want to end up with extra classes that do roughly the same thing. For example, in the Cat class, the default value for hasWhiskers should be false and remain false unless they call a constructor that explicitly requires them to be specified. Then you can use a method hasWhiskers()that returns this boolean attribute.

In general, expand the class only if the new class has additional functionality (additional methods, etc.) that cannot be simply linked to the original.

+1
source

This is a liability problem: which class does what? Your "main" class probably should not know about the internal components of the "Cat" class.

, Cat, , , .

Cat , (), , . , , : ? ? /? ( , ).

+1

, .

, .

-, , ? , .

1: ,

2: (.. , ,      .)

+1

, , ? , , ?

, , . , Cat, .

+1

-, , .

:

cars ... The
attribute "sunroof" or "navi" is quite common and does not have special requirements for the car and can be part of the base class. But the siren and flash are rather unusual and are better suited if they are attributes of another extended class.

+1
source

All Articles