Note that there are some explanatory texts on larger screens.

plurals
  1. PORefactoring abstract Java class with many child classes
    primarykey
    data
    text
    <p>I'm looking for ideas on the best way to refactor this scenario (better design, minimal effort). Starting from the following example abstract class (actual has many more fields, methods and abstract methods) :</p> <pre><code>abstract class Car { private int manufactureYear; // ... many more fields that are hard to clone public Car(int manYear) { this.manufactureYear = manYear; } abstract public Color getColor(); abstract public int getNumCylinders(); } </code></pre> <p>There are so many child classes (say 100) that extend this class. These child classes are considered like 'specs' for the cars. Here are two examples :</p> <pre><code>class CarOne extends Car { private static Color COLOR = Color.Red; private static int CYLINDERS = 4; public CarOne(int manYear) { super(manYear); } public final Color getColor(); { return COLOR; } public final int getNumCylinders() { return CYLINDERS; } } class CarOneThousand extends Car { private static Color COLOR = Color.Black; private static int CYLINDERS = 6; public CarOneThousand(int manYear) { super(manYear); } public final Color getColor(); { return COLOR; } public final int getNumCylinders() { return CYLINDERS; } } </code></pre> <p>During runtime car objects get instantiated and used:</p> <pre><code>CarOne carObject = new CarOne(2009); carObject.getColor(); carObject.getNumCylinders(); </code></pre> <p>However, after getting some external data, I discover that the car was repainted and the engine changed. The new specs for the car become: </p> <pre><code>class ModCar extends Car { private static Color COLOR = Color.Blue; private static int numCylinders = 8; public ModCar (int manYear) { super(manYear); } public final Color getColor(); { return COLOR; } public final int getNumCylinders() { return numCylinders; } } </code></pre> <p>So really need to "apply" these specs to the new <code>carObject</code> without modifying existing fields such as <code>manufactureDate</code>. The problem is how to minimize the code of changes to those 100+ child classes (preferably leave them untouched) while being able to update the <code>carObject</code> during runtime.</p> <p>N.B. I was given to work on this code so I didn't write it in this condition to begin with.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload