Creating a new object creates a new instance of that class. Because two different objects are separate instances, things can happen inside each one without affecting the other. We've already seen many cases where instances matter. For example, inside the constructor, like this:
JAVA
publicclassPet {
String name;
int weight;
Pet(String name, int weight) {
this.name = name;
this.weight = weight;
}
}
The this keyword refers to the current instance of the class. Sometimes, you will want data or methods to remain inaccessible to other classes. This is where access modifiers come in to play.
Access Modifiers
Access modifiers change how a class, method, or property can be accessed by other classes. For example, we can restrict direct access to name and weight by marking them as private:
In this particular instance, it doesn't really add much value, but sometimes you want to do some validation or calculations using the property. In that case, you definitely want to restrict direct access of a property and instead make users go through specific methods.
Public
The public access modifier is usable on classes, properties, methods, and constructors. This makes them accessible for all classes:
JAVA
publicclassPet {
public String name;
publicint weight;
Pet(String name, int weight) {
this.name = name;
this.weight = weight;
}
}
Private
The private access modifier is usable on properties, methods, and constructors. They make the code only accessible within that class:
To access these values, the class needs to provide a public method inside that returns that value.
Protected
The protected access modifier is usable on properties, methods, and constructors. They make the code only accessible within that class and any class that extends it: