Reputation: 89
So lets say I have a class like this:
public class MyClass
{
public int myInt = 5;
}
Now I don't want this to happen:
MyClass myObject = new MyClass();
myObject.myInt = 10;
I just want "myInt" to be read only. How can I do that?
Upvotes: 0
Views: 1436
Reputation: 124215
I just want "myInt" to be read only
make it final
public class MyClass
{
public final int myInt = 5;
}
or private
and add getter method
public class MyClass
{
private int myInt = 5;
public int getMyInt(){
return myInt;
}
}
Both solutions have pros but also cons:
reflection
.Upvotes: 4
Reputation: 360
AFAIK there is no way to do this. Make myInt private and declare a public getter function. What are you trying to accomplish?
public class MyClass
{
private int myInt = 5;
public int getInt() { return myInt; }
}
Upvotes: 0
Reputation: 1306
Make the variable private and add a getter method.
public class MyClass
{
private int myInt = 5;
public int getMyInt(){
return this.myInt;
}
}
MyClass myObject = new MyClass();
myObject.getMyInt(); //This will return 5
Upvotes: 0
Reputation: 272467
Use private
to make it inaccessible, or make it final
to make it immutable.
Upvotes: 2