JAVA

제네릭 타입의 상속과 구현

연93 2022. 10. 12. 14:32
// 제네릭 타입 선언
public class Product<T, M> { 
	private T kind;
	private M model;
	
	public T getKind() { return this.kind;}
	public M getModel() { return this.model;}
	
	// setKind(Tv kind)
	public void setKind(T kind) { this.kind = kind;}
	// setModel(String model)
	public void setModel(M model) { this.model = model;}
}

class Tv {}

상속 클래스

//제네릭 부모클래스 상속시 자식클래스는 부모의 타입파라미터를 반드시 사용해야 한다. 추가도 할수있다.
public class ChildProduct<T, M, C> extends Product<T, M> {
	private C company;  // String company;
	public C getCompany() { return this.company; }   // String getCompany()
	public void setCompany(C company) { this.company = company;} // setCompany(String company)
}

인터페이스

public interface Storage<T> {
	public void add(T item, int index);
	public T get(int index);
}

인터페이스 구현

public class StorageImpl<T> implements Storage<T> {

	private T[] array; // Tv[] array;
	
	public StorageImpl(int capacity) {
		// this.array = (Tv[]) (new Object[capacity]);
		this.array = (T[]) (new Object[capacity]);
	}
	
	@Override
	public void add(T item, int index) { // add(Tv item, int idex)
		array[index] = item;
		
	}

	@Override
	public T get(int index) {  // Tv get(int index)
		// TODO Auto-generated method stub
		return array[index];
	}

}

 

실행클래스

public class ChildProductAndStorageExample {

	public static void main(String[] args) {
		ChildProduct<Tv, String, String> product = new ChildProduct<>();
		product.setKind(new Tv());
		product.setModel("SmartTV");
		product.setCompany("Samsung");
		
		//필드 다형성
		Storage<Tv> storage = new StorageImpl<Tv>(100);
		storage.add(new Tv(), 0);
		Tv tv = storage.get(0);

	}

}

'JAVA' 카테고리의 다른 글

중첩클래스와 중첩 인터페이스  (0) 2022.10.15
람다식  (0) 2022.10.12
제네릭 와일드카드 타입  (0) 2022.10.12
제한된 타입 파라미터  (0) 2022.10.12
제네릭 메소드의 멀티 파라미터타입을 사용한 비교  (0) 2022.10.12