1

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);
1
  • how are you trying to create the instance, please provide that. Commented Jan 8, 2016 at 6:05

3 Answers 3

2

No it is not breaking the encapsulation of classes. This can be an example of structural design pattern where you are changing the nature of a class without actually exposing the implementation of the class to the client.

Sign up to request clarification or add additional context in comments.

2 Comments

Would you say that this is any one of the named design patterns, or close to being one of them?
Have look at Dependency Injection and construction setter. Though your pattern does not exactly match any design pattern, but resembles to DI and can be thought as a kind of Structural Design pattern.
1

Make sure you make your fields private - as you don't want anyone modifying the values directly. Other than that, your code looks fine.

Comments

0

I don't understand how is this code breaks encapsulation. As your research is on constructor chaining, this code is well and good. Otherwise I would have suggested to create Box and Contents separately and provide a Contents setter in Box class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.