3

In java, is it possible to change an Object instance from within a method of its class? I would like to do something like this:

public void setMix(MyColor[] colors){ MyColor colorMix = MyColor.colorMixer(colors); // Instead of this this.red = colorMix.getRed(); this.blue = colorMix.getBlue(); this.green = colorMix.getGreen(); // I would like to do something like: // this = colorMix; // which is not allowed } public static MyColor colorMixer(MyColor[] colors){ int red = 0; int green = 0; int blue = 0; ... // Here I work with the colors array to compute three new components return new MyColor(red, green, blue); } 

Is there a nice way to do that? Thanks a lot!

[I'm sure this question should have been answered before, but I couldn't find it, I'm sorry if it's the case]

1
  • No. That is not possible. It really depends on what you want to do specifically. You could replace all the references to the current object with a clone/instance of the one you create inside that class, but I'm not sure if that is what you want Commented Apr 6, 2011 at 13:07

3 Answers 3

3

What you are trying to do (reassigning this) is not possible, at least not in java.

Suppose you have following class:

class Foo { MyColor color; public Foo(Mycolor color) { this.color = color; } } 

And the following instances:

MyColor color = new MyColor(); Foo foo = new Foo(color); 

Suppose you could reassign this in MyColor somehow, then what you would get is a new instance of MyColor, but foo.color would still point to the old MyColor instance.

What you can do instead is just let the color instance change it's internal state. That way every other object which holds a reference to that color instance will have the "new" color object.

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

Comments

1

In java, is it possible to change an Object instance from within a method of its class? I

Yes you can , and here is the most common example

class Person{ String name; public String getName() { return name; } public void setName(String name) { this.name = name;//setting name } } 

if you want to assign something to this then its not possible its final

1 Comment

you changed a member of a object, not replacing the object with a new one inside the object's method! wrong answer i think!
0

Doing this = new MyColor() is not possible in an instance method. It seems that you need a factory, a static method like Integer.valueOf(2), to access configured instance of a class.

If you want to configure an objet in several steps, the pattern Builder is a good start.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.