캡슐화와 접근 제한자

Java로 배우는 객체 지향 프로그래밍 입문

Sani Yusuf

Lead Software Engineering Content Developer

캡슐화 이해하기

  • 캡슐화는 모바일 기기로 비유할 수 있음
  • 화면, 스피커 등 공개된 기능만 사용 가능
  • 내부 동작은 사용자에게 완전히 숨김

모바일 폰

Java로 배우는 객체 지향 프로그래밍 입문

public 속성

  • public 속성은 객체 인스턴스로 접근 가능

  class Car {
    // Public property
    public String color;


// Public constructor public Car(String color){ this.color = color; } }

    public class Main {

      // main method
      public static void main(String[] args) {
          Car myCar = new Car("brown");
          // Can access public members 
          // from object instance
          System.out.println(
            myCar.color); // Brown
        }
      }

Java로 배우는 객체 지향 프로그래밍 입문

private 속성

  • private 속성은 객체 인스턴스로 접근 불가
  • private 속성은 클래스 내부에서만 사용

  // Car class
  class Car {
     public String color;

// Private properties private String model;
public Car(String color){ this.color = color; } }

    // Main class
    public class Main {
      // main method
      public static void main(String[] args) {
          Car myCar = new Car("brown");
          // Calling private properties causes errors        
          System.out.println(
            myCar.model); // Java compilation error
        }
      }


Java로 배우는 객체 지향 프로그래밍 입문

public 메서드


  // Car class
  class Car {
      public String color;
      private String model;

      public Car(String color){
          this.color = color;
      }

      // Public method
      public String getModel(){
          return this.model;
      }    
  }    

Java로 배우는 객체 지향 프로그래밍 입문

private 메서드


  class Car {


// Private method, "calculateSpeed" can only be used within "Car" class private calculateSpeed(){ // Trademarked formula code } public int getSpeed(){ // "calculateSpeed" can be used anywhere within "Car" class return this.calculateSpeed(); } }
Java로 배우는 객체 지향 프로그래밍 입문

static 메서드

  • static 속성은 객체 생성 없이 접근 가능
  • 보통 공용 코드/라이브러리에 사용

   // Formula class 
   static class Formula {

     // Method for calculating square
     static int getSquare(int number) {
        return number * number;
      }
   }





  // Main class 
  public class Main {

    public static void 
      main(String[] args) {
          // We can use "getSquare" 
          // without an object instance
        System.out.println(
          Formula.getSquare(5)); // 25
      }
  }

Java로 배우는 객체 지향 프로그래밍 입문

정리

  • 접근 제한자: public, private, static
  • 접근 제한자는 애플리케이션 보안을 강화
  • static은 인스턴스 없이 클래스 사용 가능
Java로 배우는 객체 지향 프로그래밍 입문

연습해 봅시다!

Java로 배우는 객체 지향 프로그래밍 입문

Preparing Video For Download...