java oop 11 인스턴스 메서드와 static메서드

bitcogo·2022년 4월 10일
0

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

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

두 메서드의 차이: iv 사용여부

인스턴스(객체)는 iv 묶음
-> iv,im 사용시 객체생성이 반드시 필요

public class Oop11_staticInstanceMethod {

 public static void main(String[] args) {

	//객체생성없이 클래스메서드 호출
	System.out.println(MyMath2.add(200L, 300L));
	MyMath2 mm = new MyMath2();//인스턴스(객체) 생성
	mm.a = 200L;
	mm.b = 100L;
	System.out.println(mm.add());//인스턴스메서드 호출
 }
}

class MyMath2{
  long a,b;//iv

  long add() {//인스턴스 메서드
      return a + b;//iv
}
               //lv
static long add(long a,long b) {//클래스메서드(static메서드)
	return a + b;//lv
	}
}

class TestClass2 {
  int iv;
  static int cv;

  void instanceMethod() {
      System.out.println(iv);
      System.out.println(cv);
  }

  static void staticMethod() {
    //System.out.println(iv); 에러! iv사용불가
      System.out.println(cv);
  }
}

class TestClass{
  void instanceMethod() {}//인스턴스메서드
  static void staticMethod() {}//static메서드

  void instanceMethod2() {//인스턴스메서드
      instanceMethod(); //인스턴스메서드 OK
      staticMethod(); //static메서드 OK
  }

  static void staticMethod2() {//static메서드
    //instanceMethod(); 에러! 객체생성이 됐다는 보장이 없다.
      staticMethod(); //static메서드 OK
  }
}
profile
공부하고 기록하는 블로그

0개의 댓글