public class Calculator {
public static int num1 = 5;
// static 멤버 변수
public int num2 = 10;
// static 없이 선언하였다.
public static void Add(){
System.out.println("Add()");
}
public static void main(String[] args) {
System.out.println(Calculator.num1);
// 이미 메모리에 static변수가 할당되어 있어 인스턴스 생성없이 바로 사용/접근
Calculator cal = new Calculator();
System.out.println(cal.num2);
// static이 아닌경우 클래스 내부의 자원에 접근하려면 아래처럼 해당 클래스의 인스턴스를 생성하고 접근
❌cal.Add();
// The static method Add() from the type CalculatorEx should be accessed in a static way
// static method내에서는 인스턴스 멤버들을 직접 사용 할 수 없다.
Add();
}
}
속성을 사용하지 않는 메소드를 쓸 때 사용
해당 클래스의 객체를 생성하지 않고도 static자원에 접근이 가능하다.
static이 붙은 멤버변수와 메소드, 초기화 블럭은 인스턴스를 생성하지 않고도 사용할 수 있다.
모든 인스턴스에 공통적으로 사용되는 클래스 변수가 된다.
static 클래스 변수는 인스턴스를 생성하지 않고도 사용 가능하다.
클래스가 메모리에 로드될 때 생성된다.
static메서드 내에서는 인스턴스 멤버들을 직접 사용할 수 없다.
@Controller
@RequestMapping("/eagles")
public class EaglesController {
EaglesDao eDao = new EaglesDao();
//⭐⭐
@GetMapping("/home")
public String home() {
return "eagles/home";
}
@GetMapping("/list")
public String list() {
List<Eagles> list = eDao.getEaglesList();
return "eagles/list";
}