[Java] Referencing and Calling Members

조현호_ChoHyeonHo·2025년 1월 2일

같은 클래스에 속한 멤버들 간에는 별도의 인스턴스를 생성하지 않고도 서로 참조 또는 호출이 가능하다. 단, 클래스 멤버가 인스턴스를 참조 또는 호출하고자 하는 경우에는 인스턴스를 생성해야 한다.
그 이유는 인스턴스멤버가 존재하는 시점에 클래스멤버는 항상 존재하지만, 클래스멤버가 존재하는 시점에는 인스턴스멤버가 존재할 수도 있고 존재하지 않을 수도 있기 때문이다.

Code

public class TestClass {
    void instanceMethod(){} // instance method
    static void staticMethod(){} //static method(class method)

    void instanceMethod2(){ // instance method
        instanceMethod(); // call another member instance method 
        staticMethod(); // call another member static method(class method)
    }

    static void staticMethod2(){
        instanceMethod(); // error! static method cannot call static method.
        staticMethod(); // this is ok. Static method can only call static method.

    }
}

This is same with instance vars and static vars.


Tip.

MemberCall c = new MemberCall();
int result = c.instanceMethod1();

This can be shortened like following.

int result = new MemberCall().instanceMethod1();
profile
Behold the rabbit hole

0개의 댓글