Java 길찾기/이것이 자바다

[Java] 제네릭 타입의 상속 구현

Kindbeeeear_ 2022. 4. 7. 18:26

제네릭 타입도 다른 타입과 마찬가지로 부모 클래스가 될 수 있다. 다음은 Product<T, M> 제네릭 타입을 상속해서 ChildProduct<T, M> 타입을 정의한다.

public class ChildProduct<T, M> extends Product<T, M> { ... }

 

자식 제네릭 타입은 추가적으로 타입 파라미터를 가질 수 있다. 다음은 세 가지 타입 파라미터를 가진 자식 제네릭 타입을 선언한 것이다.

public class ChildProduct<T, M, C> extends Product<T, M> { ... }
// Product.java -- 부모 제네릭 클래스
public class Product<T, M> {
    private T kind;
    private M model;
    
    public T getKind() { return this.kind; }
    public M getModel() { return this.model; }
    
    public void setKind(T kind) { this.kind = kind; }
    public void setModel(M model) { this.model = model; }
}
class TV {}
// ChildProduct.java -- 자식 제네릭 클래스
public class ChildProduct<T, M, C> extends Product<T, M> {
    private C company;
    public C getCompany() { return this.company; }
    public void setCompany(C company) { this.company = company; }
}

 

제네릭 인터페이스를 구현한 클래스도 제네릭 타입이 되는데, 다음과 같이 제네릭 인터페이스가 있다고 가정해보자.

// Storage.java -- 제네릭 인터페이스
public interface Storage<T> {
    public void add(T item, int index);
    public T get(int index);
}

 

제네릭 인터페이스인 Storage<T> 타입을 구현한 StorageImpl 클래스도 제네릭 타입이어야 한다.

// StorageImpl.java -- 제네릭 구현 클래스
public class StorageImpl<T> implements Storage<T> {
    private T[] array;
    
    public StorageImpl(int capacity) {
        this.array = (T[]) (new Object[capacity]);
    }
    
    @Override
    public void add(T item, int index) {
        array[index] = item;
    }
    
    @Override
    public T get(int index) {
        return array[index];
    }
}

 

다음 ChildProductAndStorageExample

// ChildProductAndStorageExample.java -- 제네릭 타입 사용 클래스
public class ChildProductAndStorageExample {
    public static void main(String[] args) {
        ChildProduct<Tv, String, String> product = new ChildProduct<T>();
        product.setKind(new Tv());
        product.setModel("SmartTv");
        product.setCompany("Samsung");
        
        Storage<Tv> storage = new StorageImpl<Tv>(100);
        storage.add(new Rv(), 0);
        Tv tv = storage.get(0);
    }
}

은 ChildProduct<T, M, C>와 StorageImpl<T> 클래스의 사용 방법을 보여준다.