Backend/Java

클래스 메서드(static 메서드)란?

surge_95 2022. 7. 7. 23:17

객체생성없이 호출할 수 있는 메서드

 

객체란? iv(instance variable)의 묶음 

 

언제 붙여야 할까?

1. 멤버변수 중 모든 인스턴스에 공통으로 사용할 때 

2.  iv(instance variable)를 쓸 필요가 없을 때 : 인스턴스변수는 객체가 반드시 존재해야만 사용할 수 있기 때문

* static 메서드는 instance 메서드를 호출할 수 없다 : static메서드는 객체 생성과 관계없이 항상 호출할 수 있는데, instance 메서드는 객체가 있어야 하기 때문(객체가 없을 수도 있어서) + 참조변수 this도 사용불가

 

class MyMath2 {
	long a, b;
    	//인스턴스 변수
	long add(){
		return a+b
	}
	//클래스(static) 메서드  
	static long add(long a, long b) {
		return a+b;
	}
}

class MyMathTest2 {
	public static void main(String arg[]) {
		//클래스(static) 메서드 호출
		System.out.println(MyMath.add(200L,100L); 
		//인스턴스 메서드 호출
		MyMath2 mm = new MyMath2(); // 객체 생성
		mm.a = 200L;
		mm.b = 300L;
		System.out.println(mm.add()); 
	}
}

출처:자바의 정석 기초 유투브 강의(남궁성의 정석코딩)