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.