A friend of mine was asked that question in his on-phone job interview a couple of days a go. I don\'t have a clue. can anyone suggest a solution? (His job interview is ov
public class Immutable {
private int val;
public Immutable(int v)
{
this.val = v;
}
public int getVal() { return this.val; }
}
Make all the constructors of that class as private to stop inheriting, Though not recommended.
Static classes can't be inherited from
Create a private constructor without parameters?
public class Base
{
private Base()
{
}
}
public class Derived : Base
{
//Cannot access private constructor here error
}
You can make your class immutable without using final keyword as:
I am providing immutable class here in Java.
class Immutable {
private int i;
private Immutable(int i){
this.i = i;
}
public static Immutable createInstance(int i){
return new Immutable(i);
}
public int getI(){return i;}
}
class Main {
public static void main(string args[]){
Immutable obj = Immutable.createInstance(5);
}
}