Hooli
Hooli

Reputation: 1195

immutable child from abstract parent

Can a final class that extends an abstract class be immutable?

For example:

public abstract class Parent {}

public final class Child extends Parent {}

Is Child immutable?

Upvotes: 1

Views: 752

Answers (2)

user784540
user784540

Reputation:

Immutablility of the Child class is not controlled by final keyword for the class declaration. To make your class immutable, design it in that way, that its state cannot be changed as the class instance has been created.

Adding final to the class declaration, just makes impossible to extend your class.

For example:

public final class Child extends Parent {

   private final String someText; // final is not necessary there, but it is a good practice, to declare fields like this as final. Because it gets its value once, and does not change later.

   public Child(String someText) {
     super(); // calling parent's constructor
     this.someText = someText;
   }

   public String getSomeText() {
     return this.someText;
   }    
}

Note, that as you have created an instance of Child class then you cannot change its contents. So, the class is immutable.

Upvotes: 1

Mena
Mena

Reputation: 48434

It's not immutable.

It just can't be extended.

Immutable classes are defined so no method can mutate their internal state, e.g. java.lang.String (which also happens to be a final class).

Final classes cannot be extended. As a by-product, that's why you can't have a final abstract class or a final interface.

This usually helps ensuring immutability, but it's only co-related.

Finally, thread-safety is yet another feature, which doesn't necessarily require immutability and has even less to do with preventing inheritance.

See here and child chapters for better insights on immutability.

Note

If your classes are completely empty through the inheritance hierarchy and your leaf class if final, it is factually immutable, since there's nothing to mutate.

It also is quite pointless, of course.

Upvotes: 4

Related Questions