seedasharp
seedasharp

Reputation: 89

Is there any way to make a object read only outside the class?

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

Answers (4)

Pshemo
Pshemo

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:

  • final will make it read only also inside class,
  • private wont guarantee that it wont be changed with reflection.

Upvotes: 4

Vlad Nestorov
Vlad Nestorov

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

wns349
wns349

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

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

Use private to make it inaccessible, or make it final to make it immutable.

Upvotes: 2

Related Questions