본문 바로가기

Java/문법

16 - 5장 제네릭의 상속

1. 제네릭 클래스의 상속

 

- 부모 클래스가 제네릭 클래스일 때, 이를 상속한 자식 클래스도 제네릭 클래스가 됨

- 제네릭 타입 변수를 자식 클래스가 그대로 물려받게 됨

- 자식 클래스는 제네릭 타입 변수를 추가해 정의 가능

 

- 부모 클래스와 제네릭 타입 변수의 개수가 동일할 때

class Parent<K,V> {
	//...
}
class Child<K,V> extends Parent<K,V> {
	//...
}

- 부모 클래스보다 제네릭 타입 변수의 개수가 많을 때 

class Parent<K> {
	//...
}
class Child<K,V> extends Parent<K> {
	//...
}

- 제네릭 클래스의 상속

package GenericMethod;

class Parent<T> {
	T t;
	public T getT() {
		return t;
	}
	public void setT(T t) {
		this.t = t;
	}
}

class Child1<T>extends Parent<T> {
	//부모의 메서드 호출 가능
}

class Child2<T,V> extends Parent<T>{
	V v;
	public V getV() {
		return v;
	}
	public void setV(V v) {
		this.v = v;
	}
}

public class GenericMethod {
	public static void main(String[] args) {
		//부모 제네릭 클래스 
		Parent<String> p = new Parent<>();
		p.setT("부모 제네릭 클래스");
		System.out.println(p.getT());
		
		//자식 클래스1
		Child1<String> c1 = new Child1<>();
		c1.setT("자식 1 제네릭 클래스");
		System.out.println(c1.getT());
		
		//자식 클래스2
		Child2<String,Integer> c2 = new Child2<>();
		c2.setT("자식 2 제네릭 클래스");
		c2.setV(100);
		System.out.println(c2.getT());
		System.out.println(c2.getV());
	}
}

 

2. 제네릭 메서드의 상속

 

-제네릭 메서드를 포함한 일반 클래스를 상속해 자식 클래스를 생성할 때도 부모 클래스 내의 제네릭 메서드는 그대로 자식 클래스로 상속

class Parent{
	public <T> void print(T t) {
    	System.out.println(t);
    }
}

class Child extends Parent [

}
Parent p = new Parent();
p.<String>print("안녕");

Child c = new Child();
c.<String>print("안녕");

 

- 제네릭 메서드의 상속

 ->부모 클래스로부터 최상위 제네릭 타입이 Number로 제한 돼 있는 print() 제네릭 메서드를  상속받아 사용

 -> Number 클래스 = 기본 자료형 6개(Byte,Short,Integer,Long,Float,Double)의 래퍼클래스의 부모 클래스

 

package GenericMethod;

class Parent {
	<T extends Number> void print(T t) {
		System.out.println(t);
	}
}

class Child extends Parent {
	
}

public class GenericMethod {
	public static void main(String[] args) {
		
		//부모 클래스에서 제네릭 메서드 이용
		Parent p = new Parent();
		p.<Integer>print(10);
		p.print(10);
		
		//자식 클래스에서 제네릭 메서드 이용
		Child c = new Child();
		c.<Double>print(5.8);
		c.print(5.8);
	}
}