AmiguelS
AmiguelS

Reputation: 855

Access permissions for variable in Java

A certain class Connection has a field int status, which indicates the status of the connection. This field should be able publicly available for read, but not for writing, as only the object itself should write to that variable. Is there a way to achieve this in Java?

Upvotes: 1

Views: 291

Answers (2)

Cootri
Cootri

Reputation: 3836

you should create public "getter" method for the private status field to prevent broken encapsulation:

private int status;
...
public int getStatus(){
    return this.status;
}

Upvotes: 3

Mena
Mena

Reputation: 48434

Yes, set it as private and use a getter method to retrieve the value (i.e. encapsulate it).

Since it's a primitive, it's not mutable through a getter method.

Upvotes: 0

Related Questions