Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mutable and immutable classes

I want to create mutable and immutable node in java, both should be the same in everything except the mutable. how to implement the base class and the two derived class of mutable and immutable classes ?

like image 329
nabil Avatar asked Mar 01 '26 01:03

nabil


2 Answers

The difference between mutable and immutable classes is that immutable classes have no setters or any other methods that modify internal state. The state can only be set in the constructor.

It would be a bad idea to call the parent class Immutable because this would no longer be true when you have subclasses. The name would be misleading:

ImmutableNode node = new MutableNode();
((MutableNode)node).change();
like image 67
Mark Byers Avatar answered Mar 03 '26 15:03

Mark Byers


All you need to do is create a single base class with protected variables

public class Base{
     protected int foo;
}

The mutable one needs to be able to set the variable

public class MutableBase extends Base{
     public void setFoo(){}
}

The immmutable one needs to be able to set the variable only once

public class ImmutableBase extends Base{
     public ImmutableBase(int foo){
          this.foo = foo;
     }
}

Most immutable classes, have methods to act on the variable inside without mutating the instance. String does this, you might want something like this

public ImmutableBase add(int bar){
     return new ImmutableBase(this.foo+bar);
}

The cool thing about this is that you give the users of your class less control/worry over the internals of each instance. This makes it easier to work with, because in Java everything is passed by object reference, so if you're passing around a String or an ImmutableBase, you don't have to worry about it being changed.

like image 32
dfb Avatar answered Mar 03 '26 14:03

dfb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!