Java shell

I had a problem understanding Java generics and simplified this example

class A<T extends B> {

    public void fun(T t) {

    }
}

class B {
    A a;

    public void event() {
        a.fun(this);
    }

}

The problem is that this raises a warning, because A is defined inside B, but A already uses it as a generic type.

My first instinct would be that my design is wrong, but in this case I cannot change it. A is like a collection, and B is like a node in a collection that users must override. Some events may occur in B that require reporting back to parent A.

But since A is defined in the general case with B, how can I avoid the compilation warning inside B.event ()

thanks

+5
source share
2 answers

code

public class A<T extends B> {
    public void fun(T t) {
    }
}

public class B {
    A<B> a;

    public void event() {
        a.fun(this);
    }
}

Warning defeated.

Cause

A specific, generic (A<T extends B>).

, . .

+11

, :

A a;

A (T).

- :

A<B> a;

A , . , - :

class A<T> {
  public void fun(T t) {

  }
}

class B<T extends B<T>> {
  A<B<T>> a;
  public void event() {
    a.fun(this);
  }
}    

:

class A<T extends B<? extends T>> {
  public void fun(T t) {

  }
}

class B<T extends B<T>> {
  A<? super B<T>> a;
  public void event() {
    a.fun(this);
  }
}

, , , . (, , ).

class A<T extends B<? extends T>> , A B. B , B<? extends T> ( , T ).

class B<T extends B<T>> "self" Java. B () . B - "class C extends <B<C>>". , C.a A<? super B<C>>.

? super , B A, B. , , A<Shape> a Circle ( Shape, B). - . A<Circle>, A<Shape> Circle.

+13

All Articles