Click here to Skip to main content
15,867,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How we can write Immutable class in java like the String class?

I want to create an object of that class with out the new keyword and calling the constructor
as such in String we can create as

String s = "Sunil";
Posted
Updated 29-Apr-14 3:24am
v2

Please refer here:

http://docs.oracle.com/javase/tutorial/[^]

and please provide code and ask specific.
This is a homework task, which we are not making ready. We'd like YOU to work that task so you can learn it.
 
Share this answer
 
Immutable classes:
1. All fields is private final.
2. Noway to modify the object after construction.
3. Object must be constructed probably that all fields must be initialized.
4. the class must be final.
For example:
Java
public final class ImmutableClass{

    private final int field1;
    private final String field2;

    public ImmutableClass(int _1, String _2) {
        this.field1 = _1;
        this.field2 = _2;
    }
  
    public int getfield1(){
        return field1;
    }
  
    public String getfield2(){
        return field2;
    }
}

Note that there are no set method and the only way to modify the fields is using constructor. Read more here
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900