Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an immutable class in Java without using final keyword [duplicate]

Tags:

java

Possible Duplicate:
Implement a final class without the “final” keyword

I want to create an immutable class in Java without using the final keyword.

like image 422
developer Avatar asked Dec 01 '22 03:12

developer


1 Answers

I think smt like should work fine

class Immutable {
    private int i;
    public static Immutable create(int i){
        return new Immutable(i);
    }
    private Immutable(int i){this.i = i;}
    public int getI(){return i;}
}

But final is preferable.

like image 76
Stan Kurilin Avatar answered Dec 05 '22 08:12

Stan Kurilin