DEV Community

FUNDAMENTOS JAVA
FUNDAMENTOS JAVA

Posted on

1

Classe genérica com dois parâmetros de tipo

Em Java, é possível declarar uma classe genérica que aceita dois ou mais parâmetros de tipo. Esses parâmetros são especificados como uma lista separada por vírgulas.

Por exemplo, a classe genérica TwoGen aceita dois parâmetros de tipo:

class TwoGen<T, V> {
    T ob1;
    V ob2;

    // Construtor que recebe objetos de tipos T e V
    TwoGen(T o1, V o2) {
        ob1 = o1;
        ob2 = o2;
    }

    // Exibe os tipos de T e V
    void showTypes() {
        System.out.println("Type of T is " + ob1.getClass().getName());
        System.out.println("Type of V is " + ob2.getClass().getName());
    }

    T getob1() { return ob1; }
    V getob2() { return ob2; }
}

Enter fullscreen mode Exit fullscreen mode

Exemplo de uso:
A classe pode ser utilizada com diferentes tipos, como mostrado abaixo:

TwoGen<Integer, String> tgObj = new TwoGen<>(88, "Generics");
tgObj.showTypes(); // Exibe os tipos de T e V

int v = tgObj.getob1();  
System.out.println("value: " + v);  

String str = tgObj.getob2();  
System.out.println("value: " + str);  

Enter fullscreen mode Exit fullscreen mode

Saída do exemplo:

Type of T is java.lang.Integer  
Type of V is java.lang.String  
value: 88  
value: Generics  

Enter fullscreen mode Exit fullscreen mode

Notas importantes:

Ao declarar TwoGen, é necessário passar dois argumentos de tipo ao criar uma instância, como neste exemplo:

TwoGen<Integer, String> tgObj = new TwoGen<>(88, "Generics");

Enter fullscreen mode Exit fullscreen mode

Aqui, T é substituído por Integer e V por String.

Os argumentos de tipo podem ser iguais:

TwoGen<String, String> x = new TwoGen<>("A", "B");

Enter fullscreen mode Exit fullscreen mode

Nesse caso, tanto T quanto V são do tipo String.

Forma geral da declaração de uma classe genérica:

class NomeClasse<ParâmetrosTipo> {
    // Implementação
}

Enter fullscreen mode Exit fullscreen mode

Forma geral para criar uma instância genérica:

NomeClasse<ArgumentosTipo> nomeVariavel = new NomeClasse<>(ArgumentosConstrutor);

Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay