Java Immutable Object Example

An Immutable object is a object that can not be changed after creation, the use of creating Immutable objects is the accepted way or creating good, reliable Java code.  

-------------CODE-----------------


class start
{
public static void main(String args[])
{
// CREATE OBJECT WITH PARAMETERS - WILL NOT BE ABLE TO CHANGE VIA SETTERS
imut newImu = new imut(63);
System.out.println("AGE : "+newImu.getAge());
}
}

//////////////////////////////////////////////////////////


final class imut
{
final int age;


/// constructor sets the permanent value 
public imut(int newAge)
{
this.age=newAge;
}


//DISPLAY AGE
public int getAge()
{
return age;
}

//ALTHOUGH THIS METHOD IS SETTER IT WILL NEVER WORK AS AGE IS FINAL.
        //THIS WILL NOT COMPILE WITH THIS METHOD IN THE CLASS
public void setAge(int newAge)
{
this.age=newAge;
}
}

--------------------------OUTPUT-----------------------------

AGE : 63




No comments:

Post a Comment