O'Reilly logo

Java 9 Cookbook by Nick Samoylov, Mohamed Sanaulla

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

Here is a very basic class that produces mutable objects:

class MutableClass{  private int prop;  public MutableClass(int prop){    this.prop = prop;  }  public int getProp(){    return this.prop;  }  public void setProp(int prop){    this.prop = prop;  }}

To make it immutable, we need to remove the setter and add the final keyword to its only property and the class itself:

final class ImmutableClass{  final private int prop;  public ImmutableClass(int prop){    this.prop = prop;  }  public int getProp(){    return this.prop;  }}

Adding the final keyword to a class prevents it from being extended, so its methods cannot be overridden. Adding final to a private property is not as obvious. The motivation is somewhat complex and has to do with the way the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required