java - 创建实例变量对象

标签 java object constructor

我是 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/

相关文章:

javascript - 为什么构造函数只能返回一个对象?

java - 执行 Html.fromHtml 后更改 TextViews 中 html 链接的样式

Java:计算随机变量的输出?

java - 有效的对象映射

javascript - 使用对象文字和默认值创建 javascript 类的最佳方法

c++ - =默认忽略访问说明符?

java - Spring Retry 中的@Retryable 注解不会触发

java - 将数据从一个数据库表复制到不同服务器上的另一表

java - 将对象数组转换为字符串数组

JavaScript:构造函数可以创建 documentElement 对象吗?