Joan Antoni
Joan Antoni

Reputation: 31

How to change an object from a method within its class

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]

Upvotes: 3

Views: 5549

Answers (3)

Lesmana
Lesmana

Reputation: 27023

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.

Upvotes: 3

yves amsellem
yves amsellem

Reputation: 7234

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.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240860

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

Upvotes: 1

Related Questions