1

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.

2 Answers 2

2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

What about creating objects in constructor (not as a parameters) , to be used later by a method . Is that correct ? Do we need to create that object directly in the method where this will be used ? thanks!
1

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.

1 Comment

I think you have understood the question wrong. The question is if he should make a copy of the object or if he can just maintain a reference to it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.