answersLogoWhite

0

Define your own class which will have all members final

& methods to return values of variable only

/*

javavishal.blogspot.com

This code shows the way to make a class immutable

*/

// The immutable class

final class VImmutableClass

{

// instance var are made private & final to restrict the access

private final int prop1;

// Constructor where we can provide the constant value

public VImmutableClass(int vprop1)

{

prop1 = vprop1

}

// provide only methods which return the instance var

// & not change the values

public int getProp1()

{

return prop1;

}

}

// class MyImmutable

public class MyImmutable

{

public static void main(String[] args)

{

VImmutableClass obj1 = new VImmutableClass(3);

System.out.println(obj1.getProp1());

// there is no way to change the values of count & value-

// no method to call besides getXX, no subclassing, no public access to var -> Immutable

}

}

User Avatar

Wiki User

13y ago

Still curious? Ask our experts.

Chat with our AI personalities

SteveSteve
Knowledge is a journey, you know? We'll get there.
Chat with Steve
MaxineMaxine
I respect you enough to keep it real.
Chat with Maxine
ViviVivi
Your ride-or-die bestie who's seen you through every high and low.
Chat with Vivi

Add your answer:

Earn +20 pts
Q: How can you create user defined immutable object in java?
Write your answer...
Submit
Still have questions?
magnify glass
imp