Access modifier
โ What does access modifier do?
Allow access or hide
class
,field
,constructor
,method
from outside class/package
Developer should not change speaker volume outside
speaker
class๐๐ป 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 class
cannot 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
public
ordefault
โ Encapsulation
- make a classโs
field
andmethod
together into acapsule
- ๐ฐ
OOP
Access modifier
helpsencapsulation
safeby limiting access to
field
andmethod
insidecapsule
- โ๏ธ
field
should beprivate
private field
:field
should not be altered from outside classfield
should be accessed throughmethod
- ๊ณ์ข์์ ์ ๊ธ, ์ถ๊ธ์ ํ๊ธฐ ์ํด ๋ฒํผ์ ๋๋ฅด์ง ์ฐ๋ฆฌ๊ฐ ์ง์ ์์ก์ ๋ฐ๊ฟ์๋ ์์!
- ์
๊ธ, ์ถ๊ธ์ ๋ฒํผ์ ํตํด์ โก๏ธ
field
์ ๊ทผ์method
๋ฅผ ํตํด์
- โ๏ธ make the most
method
private
- hide
methods
that should not be altered from outside class - limit access to
method
from outside - ๊ผญ ํ์ํ
method
๋ง ๋ ธ์ถํ๊ธฐ - ์ฌ์ฉ์๋ ์ ๊ธ, ์ถ๊ธ๋ง ๊ฐ๋จํ๊ฒ ํ๊ณ , ๊ธ์ก์ด ์ ํจํ์ง/์์ก์ด ์ถฉ๋ถํ์ง ๋ฑ ๋ก์ง์ ์จ๊น
- hide
โ what is a good Encapsulation?
field
andmethod
in oneclass(capsule)
field
are privatefield
should be accessed through method- only required
method
should be accessible from outside - limited access to
method
as well
โ
โ
This post is licensed under CC BY 4.0 by the author.