I'm trying to create Objects. My code is something akin to:
public abstract class Fruit {
private static final Colour DEFAULT_APPLE_COLOUR = red; //let's pretend this is possible
public static Fruit newInstance(char type){
Colour myColour = DEFAULT_APPLE_COLOUR;
switch(type){
case ('a'): return new Apple(myColour);
//and onward, until default, etc.
then I have
public class Apple extends Fruit {
private final Colour c;
public Apple(Colour c){
this.c = c;
}
}
Now, I established that DEFAULT_APPLE_COLOUR
is red, and then use it to create a new Apple. This works just fine. Plus if I want to have it be another colour, I can just make myColour
become yellow
if I want to, while still being able to call for a default value easily.
However, what the difference between delcaring DEFAULT_APPLE_COLOUR
in class Fruit
and doing so directly on class Apple
, something akin to:
public class Apple extends Fruit {
private final Colour c;
private static final Colour DEFAULT_APPLE_COLOUR = red;
public Apple(Colour c){
this.c = c;
}
public Apple Apple(){
return new Apple(DEFAULT_APPLE_COLOUR);
}
}
In the latter, am I essentially creating several objects , thus creating the same DEFAULT_APPLE_COLOUR
variable as many times as I create Apples, or since it's static it's the same variable being applied to all Objects Apple? What exactly is the difference/best way to go about it ?
I think it's not the best idea for your Fruit
class to know details about child class implementations. Image the you have dozens of Fruit
s, each with some default parameters. In this case you have to hold all of these constants inside of the Fruit
class. Moreover, I don't think that you need this constant at all. The default constructor will do the job.
public class Apple extends Fruit {
private final Colour c;
public Apple(Colour c) {
this.c = c;
}
public Apple() {
this(Colour.RED);
}
}
And the factory method will look like this:
public static Fruit newInstance(char type){
....
switch(type){
case ('a'): return new Apple();
}
You encapsulate the default behavior to the Fruit
implementation, and you still have a way to change this behavior using the main constructor.
What about your factory method, I wouldn't have it inside the Fruit
class for the same reason: you parent class depends on child classes and it breaks the Open/closed principle. My suggestion is to create a FruitFactory
that will deal with instantiating of your fruits.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments