Last active
January 20, 2017 13:23
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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