[Java] Static method & Instance method

조현호_ChoHyeonHo·2024년 12월 31일

Definition

  • static method: method with static.
  • instance method: method without static.

Rules on "Static"

  1. 클래스를 설계할 때, 멤버변수 중 모든 인스턴스에 공통적으로 사용하는 것에 static을 붙인다.
  2. 클래스 변수는 인스턴스를 생성하지 않아도 사용할 수 있다.
  3. 클래스메서드는 인스턴스변수를 사용할 수 없다. (그러나, 인스턴스변수나 인스턴스메서드에서는 static이 붙은 멤버들을 사용하는 것이 언제나 가능하다. 인스턴스 변수가 존재한다는 것은 static이 붙은 변수가 이미 메모리에 존재한다는 것을 의미하기 때문이다.)
  4. 메서드 내에서 인스턴스변수를 사용하지 않는다면, static을 붙이는 것을 고려한다. (메서드 호출 시간이 짧아지기 때문에 효율이 높아진다.)

Code: MyMathTest.java

class MyMath{
    long a, b;

    long add(){ return a + b; } // a, b are instance vars.

    static long add(long a, long b){ return a + b; } // a, b are local vars.
}

public class MyMathTest {
    public static void main(String[] args) {
	    // no problem even there is no instance of MyMath class since it uses class method.
        System.out.println(MyMath.add(100L, 200L)); 

        MyMath mm = new MyMath();
        mm.a = 200;
        mm.b = 400;
        System.out.println(mm.add());
    }
}

Result

300
600
profile
Behold the rabbit hole

0개의 댓글