static 그리고 접근제한자

static

  • static 멤버는 class 안에 실제로 존재
    • 즉, object의 선언 없이 사용 가능한 멤버
public class Test{
    static int s = 0;
    int t = 0;

    public static void print1(){
        System.out.println("s = " + s);
//      System.out.println("t = " + t);
//      non-static member 접근 불가
    }

    public static void print2(){
        System.out.println("s = " + s);
        System.out.println("t = " + t);
    }
}
  • Java에서의 프로그램은 class들의 집합이기 때문에 main 함수 역시 class 내에 존재해야 함
    • 하지만 class의 객체 생성 없이 main method는 실행되어야 하기 때문에 항상 static으로 선언되어야 함
  • static 멤버 변수의 접근 방법?
    • 'object명'. 과 같이 해도 정상작동하는 경우 많으나, 엄격한 compile 규칙을 따른다면 틀린 것
    • 따라서 class에 속하는 멤버이므로, '클래스명'. 과 같이 접근하는 것이 정석
public class Test {
    static int s = 10;
    int t = 0;
    
    public static void print1() {
        System.out.println("s = " + s);
    }
    
    public void print2() {
        System.out.println("s = " + s);
        System.out.println("t = " + t);
    }
    
    public static void main(String[] args) {
        Test test1 = new Test();
        test1.t = 100;
        test1.print2

        // static 멤버 접근 방법
        Test.s = 100;
        Test.print1();
    }
}
  • static 멤버의 용도
    • main method
    • 상수 혹은 클래스 당 하나만 유지하고 있으면 되는 값
      • ex) Math.PI, Systemo.out
    • 순수하게 기능만으로 정의되는 method
      • ex) Math.abs(k), Math.sqrt(n), Math.min(a, b)



접근 제어: public, private, default, protected

  • public: 클래스 외부에서 접근이 가능
  • private: 클래스 내부에서만 접근 가능
  • default: 동일 패키지에 있는 다른 클래스에서 접근 가능
  • protected: 동일 패키지의 다른 클래스와 다른 패키지의 하위 클래스에서도 접근 가능

데이터 캡슐화

  • 모든 데이터 멤버를 private으로 만들고 필요한 경우 public한 get/set method를 제공
  • 객체가 제공해주는 method를 통하지 않고서는 객체 내부의 데이터에 접근할 수가 없음
    • 함부로 데이터를 접근하거나, 수정할 수 없음
  • 이것이 data encapsulation 혹은 information hiding


'Software Convergence > Java' 카테고리의 다른 글

Object 클래스와 Wrapper 클래스  (0) 2018.11.13
다형성: Polymorphism  (0) 2018.11.05
상속의 단점과 Strategy Pattern  (0) 2018.09.03
Generic 자료형 실습  (0) 2018.07.12
instanceof / encapsulation  (0) 2018.07.04

+ Recent posts