I'm new to OOP and I'm trying to create two objects at the same time, with a HAS-A relationship. I have a Box object, which has a Contents object inside it, and I'm struggling with how a constructor should deal with that sensibly. My research has mostly dug up things about constructor chaining within a single class. The contents object also picks a ContentsType out of an enum:
Box:
public class Box {
double volume;
Contents contents;
public Box(int inputVolume, String inputContInfo, ContentsType inputContType){
this.volume = inputVolume;
contents = new Contents(inputContInfo, inputContType);
}
}
Contents:
class Contents {
ContentsType contType;
String contInfo;
Contents(String inputContInfo, ContentsType inputContType){
this.contInfo = inputContInfo;
this.contType = inputContType;
}
}
ContentsType:
public enum ContentsType {
CARGO,
GIFT,
OTHER;
}
The above Box constructor works, but is this breaking the encapsulation of the classes? It seems wrong, and I'd like to find what the accepted way to do this is. Any suggestions would be greatly appreciated!
edit: I'm just trying to create a box from its constructor, eg:
Box aBox = new Box(2, "Something", ContentsType.CARGO);