Tuesday, August 5, 2014

[Java] Creating Immutable Class

what is immutable class. A class whose object can not be modified.

So we have to make sure we have stop all the mechanism which allows user to change the stage.

* Member Variable - Make them final so no one can change state.
* Class as Final - So derived class can not override the behavior.
* No Setter method - So its can not be changed later in case you missed to  initialize in constructor.

public Final class DataReceiver
final string port_id;
public DataReceiver( String port)
this.port_id = port;

public String getPortID()
return port_number;

Above class will be used as immutable now. :)

No comments:

Post a Comment