显示信息时保留封装

时间:2017-12-06 18:04:38

标签: java oop encapsulation

假设我有以下课程来代表CarTire

public final class Tire{

    private final String brand
    private final TireType type;

    public Tire(String brand, type)
    {
      this.brand = brand
      this.type = type;      
    }

    //getters and toString() for tire attributes
}


public final class Car{

    private final String name;
    private final Tire tire;

    public Car(String name, Tire tire){
        this.name = name;
        this.tire = tire;     
    }

    public String getName(){
        return this.name;   
    } 
}

我完全清楚我的CarTire示例缺少显着的属性,但这不是我的问题的焦点,它是我能想出的最简单的MCVE

从Effective Java(p.53):

  

您是否指定格式,提供编程访问权限   toString返回的值中包含的所有信息。

在我的Car课程中,toString()方法显然会返回名称,而根据Effective Java,如上所述,我也应提供getter。我的问题是返回轮胎的细节。

问题:

鉴于Effective Java引用的建议,我如何正确地返回我的汽车的详细信息,包括轮胎用于显示目的?

我会这样做:

public Tire getTire(){
    return this.tire   
}

public String toString(){
     return  "Name:  " + this.name + " Tire: " + this.tire;   
}  

或者换句话说,当你有一个类时,在我的情况下(Tire),这也是另一个类的属性,在我的情况下(Car),当返回时要在GUI中打印的详细信息,我该怎么做以及反复封装?

3 个答案:

答案 0 :(得分:0)

检查以下代码

public class Tire
{
    private string m_brand;
    private string m_type;
    public Tire(string brand, string type)
    {
        this.m_brand = brand;
        this.m_type = type;
    }

    public string getTireBrand()
    {
        return this.m_brand;
    }

    public string getTireType()
    {
        return this.m_type;
    }

    public override string ToString()
    {
        return "brand - " + this.m_brand + ", type - " + this.m_type;
    }
}

public class Car
{
    private string m_name;
    private Tire m_tire;

    public Car(string name, Tire tire)
    {
        this.m_name = name;
        this.m_tire = tire;
    }

    public string getCarDetails()
    {
        string car = this.m_name;
        string tireBrand = this.m_tire.getTireBrand();
        string tireType = this.m_tire.getTireType();

        return "Name:  " + car + " Tire: brand - " + tireBrand + ", type - " + tireType;
    }

    public string _getCarDetails()
    {
        return "Name:  " + this.m_name + " Tire: " + this.m_tire.ToString();
    }
}

答案 1 :(得分:0)

来自书:

  

是否指定格式,提供对toString返回的值中包含的所有信息的编程访问    如果您未能执行此操作,则会强制需要此信息的程序员解析字符串。

如果你在ToString中使用了一些非常私密的信息,那么有人可能会提取它。我的说法有所不同:只使用toString 中的公共信息仅使用toString进行调试,而不是用于实现逻辑。

答案 2 :(得分:0)

这种冲突(这是冲突,你不能兼得!)可以通过决定你更重视的东西来解决。你是否重视OO,Encapsulation,Demeter法则,而不是有效Java的引用建议。

如果您重视前者,那么无法真正遵循Effective Java的建议。我甚至认为在应用程序中使用任何 getter是错误的(具有公共API的库有些不同)。

如果你更重视这个建议,那么显然你可以定义你想要的任何吸气剂。

我知道这不是一个令人满意的答案,但不要被愚弄,你可以同时拥有这两个!你不能。