Create an immutable object - Java Thread

Java examples for Thread:Thread Safe

Introduction

An immutable object is an object that, once created, doesn't change its internal state.

In the following code, the internal variables of the object are declared final and are assigned at construction.

By doing so, it is guaranteed that the object is immutable:

Demo Code

class MyClass {/*from   ww w.ja v a 2 s.c om*/
  final private String itemOrdered;
  final private int quantityOrdered;

  MyClass(String itemOrdered, int quantityOrdered) {
    this.itemOrdered = itemOrdered;
    this.quantityOrdered = quantityOrdered;
  }

  public String getItemOrdered() {
    return itemOrdered;
  }

  public int getQuantityOrdered() {
    return quantityOrdered;
  }

  public double calculateOrderTotal(double price) {
    return getQuantityOrdered() * price;
  }
}

Related Tutorials