Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutable class as a child of an immutable class

I want to have immutable Java objects like this (strongly simplified):

class Immutable {

    protected String name;

    public Immutable(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

}

In some cases the object should not only be readable but mutable, so I could add mutability through inheritance:

public class Mutable extends Immutable {

    public Mutable(String name) {
        super(name);
    }

    public void setName(String name) {
        super.name = name;
    }

}

While this is technically fine, I wonder if it conforms with OOP and inheritance that mutable is also of type immutable. I want to avoid the OOP crime to throw UnsupportedOperationException for immutable object, like the Java collections API does.

What do you think? Any other ideas?

like image 801
deamon Avatar asked Mar 22 '10 16:03

deamon


People also ask

Can immutable class having mutable reference?

If you want to encapsulate a mutable object into an immutable one, then you need to: Create a copy of the mutable object (i.e. via copy constructor, cloning, serialization/deserialization, etc.); never store the reference to the original mutable object. Never return the mutable object.

Can we make immutable class mutable in Java?

Immutable class in java means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable.

What is mutable immutable class?

A mutable object can be changed after it's created, and an immutable object can't. That said, if you're defining your own class, you can make its objects immutable by making all fields final and private. Strings can be mutable or immutable depending on the language.


1 Answers

Your subclass is bad because it violates the Liskov substitution principle. Don't do it.

like image 161
les2 Avatar answered Sep 27 '22 20:09

les2