简体   繁体   中英

Java generics restrictions with interfaces

abstract class

public abstract class Animal {

private int id;
private String name;

public Animal(int id, String name) {
    this.id = id;
    this.name = name;
}}

_child of animal 1

public class Tiger extends Animal implements Dangerous {

public Tiger(int id, String name) {
    super(id, name);
} }

_child of animal 2

public class Panda extends Animal implements Harmless{

public Panda(int id, String name){
    super(id, name);
}}

_ Two attribute interfaces

public interface Dangerous {}
public interface Harmless {}
public class Zoo {

public static <T extends Animal & Harmless> void tagHarmless(Animal animal) {
    System.out.println("this animal is harmless");
}

public static <T extends Animal & Dangerous> void tagDangerous(Animal animal) {
    System.out.println("this animal is dangerous");
}}
public class App {
public static void main(String[] args) {

    Animal panda = new Panda(8, "Barney");
    Animal tiger = new Tiger(12, "Roger");

    Zoo.tagHarmless(panda);
    Zoo.tagHarmless(tiger);

}}

-result

this animal is harmless
this animal is harmless

Process finished with exit code 0

i try to restrict the methods of the class "zoo" with the interfaces "Dangerous" and "Harmless".

with the code

public static <T extends Animal & Harmless > void tagHarmless(Animal animal).

The Tiger doesnt have this Interface, so it actually should not work, does it? But the tiger can also be added into this method tagHarmless.

I don't see the mistake.

Thanks for help.

You are declaring a generic type parameter T , but your method is never using it. Your method accepts an Animal argument, which means any Animal is acceptable.

It should be:

public static <T extends Animal & Harmless> void tagHarmless(T animal) {
    System.out.println("this animal is harmless");
}

As for your main method, you are assigning the Panda and Tiger instances to Animal variables. Therefore, changing tagHarmless as I suggested means that neither the panda nor the tiger variables can be passed to tagHarmless (since an Animal doesn't implement Harmless ).

If you change your main to:

Panda panda = new Panda(8, "Barney");
Tiger  tiger = new Tiger(12, "Roger");

Zoo.tagHarmless(panda);
Zoo.tagHarmless(tiger);

The call to Zoo.tagHarmless(panda); will pass compilation, and the call to Zoo.tagHarmless(tiger); will not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM