25_객체지향문법-static 메소드(클래스 메소드)

Jiyoon.lee·2024년 3월 14일
0

Java_inflearn

목록 보기
25/25

1. static한 메소드는 인스턴스를 생성하지 않아도 호출할 수 있다.

  • static 메소드 사용 : 클래스명.메소드명();
public class VendingMachine {
	public String pushProductButton(int menuId) {
        System.out.println(menuId + "를 전달받았습니다.");
        return "콜라";
    }
    
    public static void printVersion() {    // static 메소드
        System.out.println("v1.0");
    }
}

public class VendingMachineMain {
        VendingMachine.printVersion();
    }
}
  • static이 붙지 않은 메소드는 반드시 인스턴스를 생성해야만 사용할 수 있다.
  • 만약, "VendingMachine.pushProductButton(100);" 코드를 추가하면 컴파일 오류가 발생한다. 해당 메소드는 static하지 않기 때문
  • static 메소드는 "레퍼런스 변수명.static메소드();"로도 실행할 수 있지만, 바람직하지 않음

0개의 댓글