我是 OOP 的新手,我想同时创建两个具有 HAS-A 关系的对象。我有一个 Box 对象,其中有一个 Contents 对象,我正在为构造函数应该如何明智地处理它而苦苦思索。我的研究主要是在单个类中挖掘有关构造函数链接的内容。内容对象还从枚举中选择一个 ContentsType:
盒子:
public class Box {
double volume;
Contents contents;
public Box(int inputVolume, String inputContInfo, ContentsType inputContType){
this.volume = inputVolume;
contents = new Contents(inputContInfo, inputContType);
}
}
内容:
class Contents {
ContentsType contType;
String contInfo;
Contents(String inputContInfo, ContentsType inputContType){
this.contInfo = inputContInfo;
this.contType = inputContType;
}
}
内容类型:
public enum ContentsType {
CARGO,
GIFT,
OTHER;
}
上面的 Box 构造函数可以工作,但这会破坏类的封装吗?这似乎是错误的,我想找到可接受的方法是什么。任何建议将不胜感激!
编辑: 我只是想从它的构造函数中创建一个框,例如:
Box aBox = new Box(2, "Something", ContentsType.CARGO);
最佳答案
不,它没有破坏类的封装。这可以是结构设计模式的一个示例,您可以在其中更改类的性质而不实际向客户端公开该类的实现。
关于java - 创建实例变量对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34670482/