0

Im trying to only allow specific classes to be used by the interact method. The code does not compile and does not recognize an underlying class to be part of the superclass.

Im using the following structure:

  • abstract class Interactable

  • abstract class Building extends Interactable

  • abstract class ContainerBuilding extends Building

  • class Cutter extends ContainerBuidling

Why does the code below not compile? Cutter.class is not recognized as a building class.

  public static void main ( String[] args ) {
        ActionTest.<Building>interact ( Cutter.class );
    }

    public static <T extends Interactable> void interact ( Class<T> interactableClass ) {
        // do something
    }

Does also not compile:

   public static void main ( String[] args ) {
        ActionTest.interact ( Cutter.class );
    }

    public static void interact ( Class<Interactable> interactableClass ) {
        // do something
    }
Zynic M
  • 41
  • 6
  • 1
    You would need to change the signature of the method to accept a `Class extends Interactable>`. Can you change the signature of `interact`? – Sweeper Dec 04 '19 at 10:58
  • Yes that works. What is the difference between T and ?.. ? – Zynic M Dec 04 '19 at 11:01

1 Answers1

2

In your first example, change the type of interactableClass to Class<? extends T>:

public static <T extends Interactable> void interact ( Class<? extends T> interactableClass )

That's because generics in Java are invariant, which means you cannot pass anything other than Class<Building> when you call that method as <Building>interact(...) if the parameter is declared as Class<T>.

Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92