Post

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 access speaker.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 class
  • default: same package(package private)
  • protected: same package + inherit
  • public: allow all access

βœ… Where is access modifier used?

  • field
  • method
  • contructor
  • class

βœ… Class and access modifier

  • class can only be public or default

βœ… Encapsulation

  • make a class’s field and method together into a capsule
  • 🟰 OOP
  • Access modifier helps encapsulation safe
  • by limiting access to field and method inside capsule

  • βœ”οΈ field should be private
  • private field: field should not be altered from outside class

    • field should be accessed through method
    • κ³„μ’Œμ—μ„œ μž…κΈˆ, μΆœκΈˆμ„ ν•˜κΈ° μœ„ν•΄ λ²„νŠΌμ„ λˆ„λ₯΄μ§€ μš°λ¦¬κ°€ 직접 μž”μ•‘μ„ λ°”κΏ€μˆ˜λŠ” μ—†μŒ!
    • μž…κΈˆ, μΆœκΈˆμ€ λ²„νŠΌμ„ ν†΅ν•΄μ„œ ➑️ field 접근은 methodλ₯Ό ν†΅ν•΄μ„œ
  • βœ”οΈ make the most method private
    • hide methods that should not be altered from outside class
    • limit access to method from outside
    • κΌ­ ν•„μš”ν•œ method만 λ…ΈμΆœν•˜κΈ°
    • μ‚¬μš©μžλŠ” μž…κΈˆ, 좜금만 κ°„λ‹¨ν•˜κ²Œ ν•˜κ³ , κΈˆμ•‘μ΄ μœ νš¨ν•œμ§€/μž”μ•‘μ΄ μΆ©λΆ„ν•œμ§€ λ“± λ‘œμ§μ€ μˆ¨κΉ€

βœ… what is a good Encapsulation?

  • field and method in one class(capsule)
  • field are private
  • field 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.