Guan Summy Huang
Guan Summy Huang

Reputation: 343

Initialize an object of another class in constructor

For example, I have the following class that implements the Icon interface. In the constructor, it initializes the Color object by creating a deep copy of the Color object supplied in the parameter.

   public class CircleIcon implements Icon {
        private Color iconColor;
        private int radius;

        public CircleIcon(Color iconColor, int radius) {
            this.iconColor = new Color(iconColor.getRGB());
            this.radius = radius;
        }
    }

My question is: Is this a proper way to initialize object of another class? I often see things like this in other people's code. In here, this.iconColor gets the reference of the Color object supplied in the parameter instead of its copy.

 public CircleIcon(Color iconColor, int radius) {
        this.iconColor = iconColor;
        this.radius = radius;
 }

I would like to know which way is preferred.

Upvotes: 1

Views: 15788

Answers (2)

Ghazanfar
Ghazanfar

Reputation: 1469

Let us first see the difference between them. When you do,

this.iconColor = new Color(iconColor.getRGB());

You are making a copy as you have said.
And when you do this,

this.iconColor = iconColor;

You are referring to the same object.


Which one is correct ? Both are correct.
Which one is better ? Neither. It depends on your requirements.

When should I use one over the other ?

Use a copy when,

  • Changes in the state of the iconColor instance will invalidate your own CircleIcon instance.

Use the same instance when,

  • The iconColor instance is immutable.
  • Changes in the state of the iconColor instance will not have any effect on the state of your CircleIcon instance.

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 121998

In design perspective :

The answer is depends.

If you want to give access to the caller of the constructor you should receive that in constructor.

If caller is not needed to provide that object, you create your self.

That's just matter of design.

In reference perspective :

Coming to your actual question, When you do this

this.iconColor = iconColor;

You are not at all creating new object, so it points to the same instance you passed. Unless you create new object, you are still referring to the passed object.

Upvotes: 1

Related Questions