简体   繁体   English

在抽象类中创建对象的最佳方法是什么?

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

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();    
    }
}

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 ).因此,每个继承者都将继承该状态(尽管无法访问它,因为它是private而不是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.在第二种方法中,对象的状态在继承者的构造函数中初始化,并且可能您被迫colorlocation声明为protected因为您将无法访问该状态。

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.如果你想让每个孩子定义自己的状态,第二个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM