static메소드와 인스턴스 메소드

ColinSong·2020년 10월 18일
1

Java의정석(기초)

목록 보기
11/25
post-thumbnail

static메소드와 인스턴스 메소드

MyMath2.java

class MyMath2 {
      long a, b;

      long add() { //인스턴스 메소드
          retun a + b;
      }

      static long add(long a, long b) { //클래스메소드(static메소드)
          return a + b;// a,b는 지역변수(Local Variable)
      }
  }
  • 둘의 차이는 Instance Variable의 사용 여부

MyMath2Test.java

  class MyMath2Test {
      public static void main(String args[]){
          
          System.out.print(MyMath2.add(200L, 100L));//클래스메소드 호출
          //클래스 메소드는 객체 없이 호출 가능
          
          MyMath2 mm = new MyMath2(); //인스턴스 생성
          mm.a = 200L;
          mm.b = 100L;
          System.out.println(mm.add()); //인스턴스메소드 호출
      }
  }

객체란?

  • Instance Variable (iv)의 묶음

인스턴스 메소드

  • 인스턴스 생성 후 '참조변수.메소드이름()'으로 호출
  • 인스턴스 멤버(iv,im)와 관련된 작업을 하는 메소드
  • 메소드 내에서 인스턴스 변수(iv) 사용가능

static메소드(클래스메소드)

  • 객체 생성없이 '클래스이름.메소드이름()'으로 호출
  • 인스턴스 멤버(iv,im)와 관련 없는 작업을 하는 메소드
  • 메소드 내에서 인스턴스 변수(iv)사용 불가
  • Math.random(), Math.round ....

static을 붙여야 할 때?

  • 속성 중에 공통적인 속성
   class Card {

      String kind; //무늬
      int Number; //숫자

      static int width = 100; //폭
      static int height = 250; //넓이
 }

ex) 게임 카드로 예를 들어보자. 카드를 객체화 한다고 가정했을 때,
카드의 폭과 넓이는 바뀌지 않지만 카드의 무늬와 숫자는 바뀐다.

  • 인스턴스 멤버(iv,im)을 사용하지 않을 때.
    iv : Instance Variable
    im : Instance Method
   class MyMath2 {
      long a, b;

      long add() {
      return a + b;  //a, b는 인스턴스 변수
      }

      long add(long a, long b) { // a,b는 지역변수
      return a + b;
      }
  }

메소드간의 호출과 참조

  • static 메소드는 인스턴스 변수(iv)를 사용할 수 없다.
  class TestClass2 {
      int iv;
      static int cv;

      void instanceMethod() { //인스턴스 메소드
          System.out.println(iv); // 인스턴스 변수를 사용할 수 있다.
          System.out.println(cv); //클래스 변수를 사용 할 수 있다.

     static void staticMethod() { //인스턴스 메소드
          System.out.println(iv); // Error!! : 인스턴스 변수를 사용할 수 없다.
          System.out.println(cv); //클래스 변수를 사용 할 수 있다.
      }
  }
  • static 메소드는 인스턴스 메소드(im)를 호출할 수 없다.
  class TestClass {
      instanceMethod() {} // 인스턴스 메소드
      static void staticMethod() {} //static메소드

      void instanceMethod2() { //인스턴스 메소드
          instanceMethod(); // 다른 인스턴스 메소드를 호출한다.
          staticMethod(); //static 메소드를 호출한다.

     static void staticMethod() { //인스턴스 메소드
          instanceMethod(); // Error!! : 인스턴스 메소드를 호출할 수 없다.
          staticMethod();; //클래스 변수를 호출 할 수 있다.
      }
  }
  • 인스턴스 메소드가 static 메소드, 다른 인스턴스 메소드를 호출 할 수 있다.
  • static메소드는 static메소드를 호출 할 수 있다.

Q&A

1. static메소드에 인스턴스 변수를 사용할 수 있는가?

  • "아니오."
    static메소드 호출 시 객체의 생성 여부 를 알 수 없기 때문이다.

2. static메소드에 인스턴스메소드를 호출할 수 있는가?

  • "아니오."
    static메소드 호출 시 객체의 생성 여부 를 알 수 없기 때문이다.

3. static메소드는 static 메소드는 호출가능한가?

  • "네."

References

profile
안녕하세요:)

0개의 댓글