3

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.

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

then i get a problem with the class App "Zoo.tagHarmless(panda);". Required type T , provided Animal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.