What is the best approach to create an object inside abstract class?

aviv.L :

What is the best approach to build color and location objects inside an abstract class, and why?

Approach 1

public abstract class Vehicle {
    private int vehicleId;
    private Color color; // color Object
    private Location location; // location Object

    public Vehicle() {
        color = new Color();
        location = new Location();
    }
}

public class Car extends Vehicle {
    private String type;

    public Car() {
        super();    
    }
}

Approach 2

public abstract class Vehicle {
    private int vehicleId;
    protected Color color; // color Object
    protected Location location; // location Object

    public Vehicle(){}
}

public class Car extends Vehicle {
    private String type;

    public Car(){
        super();
        super.location = new Location();
        super.color = new Color();    
    }
}
Themelis :

The difference between the two aproaches is that the first one instantiates its state in the abstract class. So every inheritor will inherit that state (though cannot access it since its private and not protected).

In the second approach the state of the object is getting initialized inside the inheritor's constructor and probably you were forced to declare color and location as protected since you would not be able to access that state.

Which approach is better? It depends... If you want every child to inherit a common state, the first one. If you want every child to define its own state, the second.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=393834&siteId=1