> For the complete documentation index, see [llms.txt](https://educacion.gitbook.io/programacion/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://educacion.gitbook.io/programacion/ud7-poo-avanzada/clases-xenericas-xenerics/wildcards.md).

# Wildcards

En Java, os **comodíns** (*wildcards*) úsanse cos **xenéricos** para indicar tipos descoñecidos ou flexibles. Escríbense co símbolo `?` e permiten traballar con distintos tipos mantendo a seguridade de tipos.

Hai tres formas principais:

* `<?>` → calquera tipo (descoñecido)
* `<? extends T>` → un tipo que é subclase de `T` (límite superior)
* `<? super T>` → un tipo que é superclase de `T` (límite inferior)

Isto é útil cando queremos escribir código máis xeral e reutilizable.

```java
class Caixa<T> {
    private T valor;

    public void gardar(T valor) {
        this.valor = valor;
    }

    public T obter() {
        return valor;
    }
}

public class Proba {
    public static void imprimirCaixa(Caixa<?> caixa) {
        System.out.println(caixa.obter());
    }

    public static void main(String[] args) {
        Caixa<Integer> c1 = new Caixa<>();
        c1.gardar(10);

        Caixa<String> c2 = new Caixa<>();
        c2.gardar("Ola");

        imprimirCaixa(c1);
        imprimirCaixa(c2);
    }
}
```

{% hint style="warning" %}
No caso anterior, **non é posible empregar T no parámetro por que so existe dentro do contexto que foi declarado**.

* `T` é un **parámetro de tipo da clase `Caixa`**
* O método `imprimirCaixa` é **estático e independente**, polo que non coñece que é `T`

Unha alternativa ao uso de wildcards vai a ser a seguinte:

```java
public static <T> void imprimirCaixa(Caixa<T> caixa) {
    System.out.println(caixa.obter());
}
```

{% endhint %}

{% hint style="warning" %}
En determinados casos é necesario o uso de ? en lugar de T ou un xenerics por que:

* **\<?> é o único tipo que instanceof pode verificar no momento de execución para clases xenéricas**
* Respecta o **type erasure** de Java, recoñecendo que en tempo de execución solo existe Caixa, non Caixa\<T>
* No equals non funciona o tipo T por que hai verificacion de tipos. No método obter() si funciona por que no comproba nada, únicamente devolve.

```java
@Override
public boolean equals(Object obj) {
    if (!(obj instanceof Caixa<?>)) 
        return false;

    Caixa<?> outra = (Caixa<?>) obj;
    return this.obter().equals(outra.obter());
}
```

{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://educacion.gitbook.io/programacion/ud7-poo-avanzada/clases-xenericas-xenerics/wildcards.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
