Reputation: 123
there is a class:
public class Rectangle {
public int width = 0;
public int height = 0;
public Point origin;
public Rectangle(Point p) {
origin = p;
}
}
As it can be seen, the class has an object of the type Point. When I declare an object of the type Rectangle,
Rectangle rectOne = new Rectangle(originOne)
where originOne is of the type Point, then after the initialisation of the object, I will have two different references to the Point reference by originOne, namely rectOne.origin and originOne. What if I want to get rid of one of the variables for the sake of making the code safer ? Is there a way to do that other than writing the constructor in such a way that no extra objects are created ?
Upvotes: 4
Views: 258
Reputation: 83205
What if I want to get rid of one of the variables for the sake of making the code safer?
You are asking this in a strange way. I presume you want to make sure that someone can't affect rectOne
by mutating originOne
later.
Is there a way to do that other than writing the constructor in such a way that no extra objects are created?
Your solution is in your question: create an extra object.
public Rectangle(Point p) {
origin = new Point(p.x, p.y);
}
or
public Rectangle(Point p) {
origin = p.clone();
}
It will have to support the clone
method for this last one. See this or another reference for what that involves.
If you want to do this without creating another object, (1) you probably can't, and (2) why are you restricting yourself from creating objects? That's kind of what what OO programming is all about.
You don't often have this same concern about String
s. Why? Because they are immutable.
Another (IMO better) solution is to make the Point
class immutable
public class Point { // possibly add "final class"
final int x;
final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Now no one can mutate a Point
, and your code becomes "safer".
Upvotes: 4
Reputation: 43023
When you use write your code the way you did it, there are no extra objects of Point
class created, you just create a new reference to the same object stored in a new variable.
If you want to make sure you don't create an additional reference to the same Point
object, you can pass X and Y of the point to your Rectangle
class and create a new object in the constructor:
public Rectangle(int x, int y) {
origin = new Point(x, y);
}
This way it makes it quite clear that you're not storing a reference to a passed parameter.
Upvotes: 2