Reputation: 1863
I have this:
public void log(Circle circOrig) {
...
}
And I'm trying to avoid doing this:
private void addPositions(PositionsLogger positionsLogger) {
...
Circle circ = new Circle(0,0,0); //`circ` could be final
circ.setPosition(0,0);
posLogger.log(circ);
...
}
By doing this:
public static void main(String[] args) {
...
posLogger.log(new (Circle(0, 0, 0).setPosition(0, 0)));
...
}
Which is obviously a compile error because log()
requires a Circle
, not a void
.
How can I avoid having to declare a local variable for such a trivial purpose?
Upvotes: 1
Views: 1228
Reputation: 9527
There is no reason why not to have local variable. When you call new
, It will create new object either way. Solution without local variable is more messy and less readable.
Variable is just pointer to memory, where "circle" is allocated. So when passing argument to your log function, you pass that pointer and inside log, you are working with created circle instance. There is no deep copy.
Upvotes: 6
Reputation: 5543
As an alternative solution you should consider extend Circle
adding a new constructor that does what you need.
You could either do that in the code of the class, if you can modify it, or in a new class.
public class ExtendedCircle extends Circle{
public class ExtendedCircle(int x, int y, int x, int positionX, int positionY){
super(x,y,z);
setPosition(positionX, positionY);
}
}
Note that I don't think that the creation of a new class is an ideal solution. It would be better to have an helper method or to keep the reference to the variable as reported in other answers.
Upvotes: 0
Reputation: 2678
Assuming you don't have access to the Circle code and don't like the overriding mechanisms (which look as ugly as having a local variable so are a bit pointless) then all you can do is define a helper method that creates the circle, sets its position and returns the circle.
I can understand why you want to do this but I think with Java being what it is, you're not going to get a brilliant solution without access to the Circle code.
Upvotes: 1
Reputation: 114
If you really want to not have a local variable, you can override the circle class like so:
posLogger.log(new (Circle(0, 0, 0){{setPosition(0, 0);}}));
Upvotes: 1