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.