Tuesday, 27 March 2018

How to create Immutable class in Java?


Following are the requirements:
        Class must be declared as final (So that child classes can’t be created)
        Data members in the class must be declared as final (So that we can’t change the value of it after object creation)
        A parameterized constructor
        Getter method for all the variables in it
        No setters(To not have option to change the value of the instance variable)


public final class Student
{
    final String name;
    final int regNo;

    public Student(String name,int regNo)
    {
        this.name=name;
        this.regNo=regNo;
    }
    public String getName()
    {
        return name;
    }
    public int getRegNo()
    {
        return regNo;
    }
}

No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...