How to create an immutable class in Java without using the final keyword

Possible duplicate:
Implement the last class without the keyword "final"

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

+3
source share
6 answers

I think smt 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 the final version is preferable.

+11
source

The final keyword will not make your class inmutable. This will avoid extending your class from another class.

public final class Foo {
   //....
}

public class Bar extends Foo {
   //COMPILATION ERROR!
}

The adecuated class project is what will make you an inmutable class, as you can see in duffymo's answer.

, final , :

class Foo {
    private final int state

   public Foo(int v) {
      this.state=v;
   }

   //....
}

, , duffymo ccould (.. , ), .

final:

public class Foo {

   private int state;


   private Foo(int v) {
       this.state=v;
   }

   public static Foo getInstance(int value) {
      return new Foo(value);
   }

}

Foo, Foo.getInstance.

Foo . , Foo.

public class Bar extends Foo {
    private int ohNopes;

    //COMPILATION ERROR!
    public Bar(int v) {
        this.ohNopes=v; 
    }
}

, , , .

+4

, , , .

Java API, java.lang.String , , , .

, :

public class MyString extends java.Lang.String {
    public MyString(String original) {
        Super(original);
    }

    @Override
    public String toString() {
        return String.valueOf(System.currentTimeMillis());
}

, java.ma.BigDecimal , . . BigDecimal , , BigDecimal, , String. BigDecimal , .

, BigDecimal :

public class MyBigDecimal extends java.math.BigDecimal {
    public MyBigDecimal(double val) {
        super(val);
    }

    private int count = 0;
    // override intValue which changes the state of this instance
    @Override
    public int intValue() {
        return count++; 
    }

    // rinse and repeat for the rest of the BigDecimal methods... 
}

BigDecimal, , , .

+3

, final, , . , , :

public class Immutable
{
    private int value;

    public Immutable(int v)
    { 
        this.value = v;
    }

    public int getValue() { return this.value; }
}
+1

(, ).

0

, .jar jar .

-1

All Articles