gpt4 book ai didi

java - 显示信息的同时保留封装

转载 作者:太空宇宙 更新时间:2023-11-04 10:52:16 27 4
gpt4 key购买 nike

假设我有以下类来表示 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》(第 53 页):

Whether or not you specify the format, provide programmatic access to all of the information contained in the value returned by 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 中打印的详细信息时,我将如何执行此操作并进行反封装?

最佳答案

检查下面的代码

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

关于java - 显示信息的同时保留封装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47680744/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com