encapsulation.md (822B)
1 +++ 2 title = 'Encapsulation' 3 +++ 4 # Encapsulation 5 Encapsulation makes sure that sensitive stuff is hidden from users. 6 7 Idea: declare class variables/attributes as private, provide public getters and setters to use the variable. 8 9 ```java 10 public class Safe { 11 private String superPrivateInfo; 12 13 public String getSuperPrivateInfo() { 14 return superPrivateInfo; 15 } 16 17 public void setSuperPrivateInfo(String newInfo) { 18 this.superPrivateInfo = newInfo; 19 } 20 } 21 ``` 22 23 Classes can be: 24 - `public`: accessible by any other class 25 - default: only accessible in same package 26 27 Attributes/methods/constructors can be: 28 - `public`: accessible by any other class 29 - `private`: only accessible within declared class 30 - default: only accessible in same package 31 - `protected`: only accessible in same package and subclasses