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
}
}
Chat with our AI personalities
A java object is a collection of methods and properties defined in the Java programming language.
No. if you wish to create an object that you plan on using in a java program then the answer is NO. You cannot initialize an object of a Java class without calling the constructor.
It means that something can be changed after it is created. Immutable means that it can't be changed.
Object Class is the parent class of all classes in java.Every class in the Java system is a descendant (direct or indirect) of the Object class.
That is used to verify whether an object is based on the specified class (or a subclass).