[Java] 노트정리 : final, static, Generic

Young eee·2023년 1월 2일

Java

목록 보기
19/22
post-thumbnail

📖 final

  • 변수 사용시 : 대입용인 경우가 많으며 대문자로 많이 사용
  • 클래스 사용시 : 상속금지, 내부 함수에서 사용시 상속했을 때 고쳐사용 금지

💻 final Ex.

public class MainClass {

	public static void main(String[] args) {
		/*
			final : 변수 , 클래스, 메소드
					== const, define
		 */
		
		final int NUMBER = 1;	//상수(변경될 수 없는 수), number는 무조건 1로 고정
		// number = 2; // 오류
		int num = NUMBER;

	}

}
//상속금지
/*final*/ class MyClass {
	// override 금지
	public /*final*/ void method() {
		
	}
}

class YouClass extends MyClass{
	public void method() {
		
	}
}

📖 static

  • static : 정적 != 동적(dynamic)

✏️변수 : 지역(local)변수, 멤버(class)변수, 매개(method)변수, 정적(static)변수

정적(static)변수 == 전역(global)변수

지역변수 : 지역에서만 활동하고 끝나면 memory stack에서 사라짐. 메모리에 무리가 안감
정적변수 : 시작과 끝을 같이 하는 변수, 프로그램의 시작과 끝을 함께함, 많이 사용하면 메모리사용이 커짐

memory(4개 공간)

stackheapstaticsystem
지역변수멤버변수정적변수
매개변수

💻 static Ex.

public class MainClass {

	public static void main(String[] args) {

		int localvar;	//지역(local)변수 (auto)
		
		MyClass my = new MyClass();
		my.membervar = 12;
		
		my.method('A');
		
		
		MyClass.stnumber = 11;	//객체생성 없이 접근 가능
		
		MyClass.st_method();
	}
	static void func() {
		int localvar;	//지역(local)변수
	}
}
class MyClass{
	int membervar;	//멤버(class)변수
	static int stnumber = 1;	// 정적변수는 멤버변수의 형태로 사용해야함
	
	public void method(char c) {	// 매개(method)변수
		int membervar = 2;
	}
	
	public void func() {
		//static int stnumber = 1; 정적변수는 로컬에서 사용할 수 없음
	}
	public static void st_method() {
		//this 접근 불가
		//super 접근 불가
		
		System.out.println("MyClass st_method");
	}
}

📖 Generic

  • Generic == template(형태)
  • 자료형의 변수
  • 같은 클래스에서 다양한 자료형을 사용하고 싶은 경우에 사용하는 요소

💻 Generic Ex.

public class MainClass {

	public static void main(String[] args) {

	//	number -> int, string, double

		Box<Integer> box = new Box<Integer>(100);
		System.out.println(box.getTemp());	// 100
		
		Box<String> sbox = new Box<String>("Hello");
		System.out.println(sbox.getTemp());	// Hello
		
		BoxMap<Integer, String> boxmap = new BoxMap<Integer, String>(1001, "홍길동");
		System.out.println(boxmap.getKey());
		System.out.println(boxmap.getValue());
		
	}

}

//원하는 글자 아무거나 적어도 되는데 대부분 대문자를 사용
class Box<T> {
	//자료형 자리에
	T temp;
	
	public Box(T temp) {
		this.temp = temp;
	}

	public T getTemp() {
		return temp;
	}

	public void setTemp(T temp) {
		this.temp = temp;
	}
}

class BoxMap<KEY, VALUE> {
	KEY key;
	VALUE value;
	
	public BoxMap(KEY key, VALUE value) {
		this.key = key;
		this.value = value;
	}

	public KEY getKey() {
		return key;
	}

	public void setKey(KEY key) {
		this.key = key;
	}

	public VALUE getValue() {
		return value;
	}

	public void setValue(VALUE value) {
		this.value = value;
	}

}

0개의 댓글