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.