Home > Back-end >  How I can make proper use of Generic?
How I can make proper use of Generic?

Time:04-22

public class GenericClass {
    public static void main(String... args) {
        Hat<Integer> marks = new Hat<Integer>();
        marks.tell(4);
        Hat<String> apple = new Hat<String>();
        apple.tell("apple");
    }
}

class Hat<T> {
    void tell(T an) {
        System.out.println(an   " is good");
    }

    void tell(String fu) {
        System.out.println(fu   " is healthy");
    }
}

How is apple.tell("apple") ambiguous? I am trying check how many different ways I can make use of Generic.

CodePudding user response:

apple.tell("apple")

is an String and

void tell(T an) {
    System.out.println(an   " is good");
}

T Become String for "apple" so compiler encounter Two String & Overloading is also there so it is ambiguous

  • Related