static method 와 instance method
class MyMath2 {
long a, b; // iv
long add() { // 인스턴스 메서드
return a + b;
}
static long add2(long a, long b) { // static(클래스) 메서드, lv(지역변수)
return a + b; // lv
}
}
public class MyMath2Test {
public static void main(String[] args) {
// 객체 생성 없이 호출 가능
System.out.println(MyMath2.add2(200L, 300L));
MyMath2 mm = new MyMath2();
mm.a = 150L;
mm.b = 250L;
// 객체 생성 후 호출 가능
System.out.println(mm.add());
}
}
static method
class.method()
- 객체 생성 없이 호출 가능
- Instance value 사용하지 않음
instance method
instance.method()
- 객체 생성 후 호출 가능
- Instance value 사용
결론
-
각 method의 매개변수 유무와 Instance value의 사용 여부를 확인하면 method를 구분할 수 있다.
-
객체는 Instance value(변수)의 묶음이다.
class MyMath2{
long a, b;
long add() { return a + b;} // iv
static long add(long a, long b) { return a + b;} // lv
static은 언제 붙일까?
-
속성(멤버 변수) 중 공통 속성에 static을 붙여 언제나 사용 가능하다.
-
인스턴스 멤버(IV, IM)를 사용하지 않는 method에 static을 붙인다.
class Test{
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); // 클래스 변수 사용 가능
}
class Test{
void im() {};
static void sm() {};
void instanceMethod() {
im();
sm(); // static method 호출 가능
}
static void staticMethod() {
im(); // ERROR:객체가 생성됐다는 보장이 없음, im() 호출은 iv를 사용하는 것과 동일
sm(); // static method 호출 가능
}
결론
static method는 instance method를 호출할 수 없고,
instance method는 static method를 호출할 수 있다.
Author And Source
이 문제에 관하여(static method 와 instance method), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@solda/static-method-와-instance-method저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)