IT/Programming / / 2023. 4. 21. 17:35

[JAVA] static class, final 사용 예제

반응형
package pckmain;

import javax.swing.JOptionPane;

/*
 * static은 클래스 내무의 멤버에만 붙일 수 있다.
 * static이 붙으면 : static멤버, class 멤버
 * static이 붙지 않으면 : non-static멤버, instance멤버
 * ============================================
 * static멤버 접근 형식은 class명.멤버변수(메소드)
 * ============================================
 * static 메소드는 non-static멤버를 호출할 수 없다.
 * 
 * 언제 static을 사용해야하는가?
 *  -> 저장필요없고  계산만 해야 할 때
 *  -> 임시적인 목적
 * 
 * <final : 변경할 수 없는>
 *  클래스 앞에 붙으면 : 상속할 수 없다.
 *  메소드 앞에 붙으면 : 오버라이드 할수 없다, 오버로드는 됨
 *  변수 앞에 붙으면 :
 *   값을 변경할 수 없다.
 *   사용자 정의 상수가 된다.
 *   상수 취급하는 변수이름은 모두 대문자
 *   띄어쓰기는 _ 사용(스네이크표기법)(기존의 것은 낙타표기법)
 *  
 *  
 *  
 *  
 */

class Test{
	String str = "인스턴스 멤버str";
	static String str2 = "클래스멤버 str";
	
	void show(){//객체 생성시 생성(힙영역)
		System.out.println(str);
		System.out.println(str2);
	}
	static void show2(){ //생성 시점의 문제, 실행시 바로 실행(메소드메모리)
		//System.out.println(str);//str2보다 늦게 생성되기 때문에 실행 오류
		System.out.println(str2);
	}
}
public class test01 {
	public static void main(String[] args) {
		Math.random();//math - class 안에 소속된 랜덤 메소드.. static으로 되어있기때문에 따로 객체생성을 하지 않아도 된다.
		JOptionPane.showInputDialog("");//joption - class도 static.., 객체생성도 됨.
		JOptionPane j = new JOptionPane();
		j.showInputDialog("");
		
		//Test show()
		Test t = new Test();
		t.show();
		
		//Test show2();
		t.show2();//static한 방법이 아님
		Test.show2();//static은 앞에 클래스명을 사용. 
		  			 //-메소드 영역에 존재하기 때문에 클래스와 같이 생성되는 시점에서 사용
		
	}
}
반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유