Skip to content

Instantly share code, notes, and snippets.

@dhust
Last active January 20, 2017 13:23
Show Gist options
  • Save dhust/9be56ccf31fb738b146241d841f5fa6f to your computer and use it in GitHub Desktop.
Save dhust/9be56ccf31fb738b146241d841f5fa6f to your computer and use it in GitHub Desktop.
Encapsulation example. Need to make the age variable private so no one can directly change it, and the setAge() method is checking for a valid age.
public class EncapsulationExample {
// variables
private int age;
// default constructor
public EncapsulationExample() {
}
// encapsulation
public void setAge (int newAge) {
if (newAge < 0) {
System.out.println("Invalid age");
} else {
age = newAge;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment