JVM의 힙 영역
에 생성된다.
인스턴스
를 생성한 뒤 호출한다.
클래스 내
에서 인스턴스 메서드
는 인스턴스 메서드
를 호출할 수 있다
인스턴스 메서드
가 생성된 시점에는 인스턴스
가 생성되었기 때문
JVM의 메서드 영역
에 생성된다.
모든 인스턴스에 공통으로 사용하는 변수, 메서드이다.
별도의 인스턴스
를 생성하지 않아도 된다.
static
키워드를 사용한다
클래스 변수
는 인스턴스를 생성하지 않아도 사용가능하다
클래스 메서드
에서는 인스턴스 메서드, 변수
를 사용할 수 없다
클래스 메서드
가 생성된 시점에 인스턴스
의 생성여부를 알 수 없기 때문package pr01;
class MyMath{
// 인스턴스 변수, 인스턴스 메서드
int a, b;
int add(){return a+b;}
int sub(){return a-b;}
int mul(){return a*b;}
int div(){mul(); return a/b;} // 인스턴스 메서드 mul 호출
// 클래스 메서드
static int add(int a,int b){return a+b;}
static int sub(int a,int b){add(1,2);return a-b;} // 클래스 메서드 add 호출, 인스턴스 메서드 add()는 호출 못함
static int mul(int a,int b){return a*b;}
static int div(int a,int b){return a/b;}
}
public class test {
public static void main(String[] args) {
// 클래스 메서드 : 인스턴스 생성없이 호출 가능
System.out.println(MyMath.add(4,2));
System.out.println(MyMath.sub(4,2));
System.out.println(MyMath.mul(4,2));
System.out.println(MyMath.div(4,2));
// 인스턴스 메서드 : 인스턴스 생성 후 호출 가능
MyMath m1 = new MyMath();
m1.a=4;
m1.b=2;
System.out.println(m1.add());
System.out.println(m1.sub());
System.out.println(m1.mul());
System.out.println(m1.div());
}
}