Access modifier
β What does access modifier do?
Allow access or hide
class,field,constructor,methodfrom outside class/package
Developer should not change speaker volume outside
speakerclassππ» Before(without access modifier)
1
2
3
public class Speaker1 {
int volume;
}
1
2
3
4
5
public class SpeakerMain1 {
public static void main(String[] args) {
speaker.volume = 200; //ππ» Can change speaker volume in main class
}
- ππ» After
- add
private main classcannot accessspeaker.volume
1
2
3
public class Speaker2 {
private int volume; //π’ add private access modifier
}
1
2
3
4
5
6
public class SpeakerMain2 {
public static void main(String[] args) {
speaker.volume = 200; //π΄ compile error
//ππ» cannot access speaker.volume
}
β Access modifier
private: same classdefault: same package(package private)protected: same package + inheritpublic: allow all access
β Where is access modifier used?
- field
- method
- contructor
- class
β Class and access modifier
- class can only be
publicordefault
β Encapsulation
- make a classβs
fieldandmethodtogether into acapsule - π°
OOP Access modifierhelpsencapsulationsafeby limiting access to
fieldandmethodinsidecapsule- βοΈ
fieldshould beprivate private field:fieldshould not be altered from outside classfieldshould be accessed throughmethod- κ³μ’μμ μ κΈ, μΆκΈμ νκΈ° μν΄ λ²νΌμ λλ₯΄μ§ μ°λ¦¬κ° μ§μ μμ‘μ λ°κΏμλ μμ!
- μ
κΈ, μΆκΈμ λ²νΌμ ν΅ν΄μ β‘οΈ
fieldμ κ·Όμmethodλ₯Ό ν΅ν΄μ
- βοΈ make the most
methodprivate- hide
methodsthat should not be altered from outside class - limit access to
methodfrom outside - κΌ νμν
methodλ§ λ ΈμΆνκΈ° - μ¬μ©μλ μ κΈ, μΆκΈλ§ κ°λ¨νκ² νκ³ , κΈμ‘μ΄ μ ν¨νμ§/μμ‘μ΄ μΆ©λΆνμ§ λ± λ‘μ§μ μ¨κΉ
- hide
β what is a good Encapsulation?
fieldandmethodin oneclass(capsule)fieldare privatefieldshould be accessed through method- only required
methodshould be accessible from outside - limited access to
methodas well
β
β
This post is licensed under CC BY 4.0 by the author.