0

I have 2 empty classes emp and reset . I have method in another class which will accept only these two classes these I need to achieve using generics . Both these classes are not related to each other in any manner.

package abstracta;

import generics.emp;
import generics.nonemp;
import generics.reset;

// A Simple Java program to show working of user defined
// Generic functions

class Test
{
    // A Generic method example
    static <T> void genericDisplay ( T element)
    {
        System.out.println(element.getClass().getName() +
                           " = " + element);
    }

    // Driver method
    public static void main(String[] args)
    {
         // Calling generic method with Integer argument
        genericDisplay(new emp());

        // Calling generic method with String argument
        genericDisplay(new reset());

        genericDisplay(new nonemp());// should not accept  . restrict this class
    }
}

i want genericDisplay not to accept nonemp class

user3675126
  • 19
  • 1
  • 8
  • this question was asked in an interview class Employee {};class User{} Call(Accepts only objects of these two classes ) – user3675126 May 22 '18 at 12:10
  • 2
    If they are not related, generics won't be able to help you. But you can overload that method so that one version accepts ``Employee`` and one takes an instance of ``User``. – f1sh May 22 '18 at 12:12
  • Please show us what you have done so far. It will make giving an answer much easier. – Dragonthoughts May 22 '18 at 12:14
  • Best way is to overload the method call with Employee and User. No need for generics, no instanceofs etc. – M.F May 22 '18 at 12:15
  • 1
    It could have been a trick question, hoping to trap you with a (syntactically invalid) union type `void someMethod(T t) {...}` – Bohemian May 22 '18 at 12:18
  • 1
    Now that you've revealed that this was an interview question, and one that seems to not have a proper answer, I'm voting to close. We will not able to get into the mind of your interviewer. If you care about their answer, you should contact them. This is not possible with Java, and I would seriously reconsider working anywhere that sets questions like this in the first place. – Michael May 22 '18 at 12:22
  • @Michael am ok with closing the question Thanks you for your inputs , i already used interface and resolved it but wanted to if this is some how possible using generics Thank you All – user3675126 May 22 '18 at 12:29

1 Answers1

1

You haven't shown us your code, but the common solution to this is to create a common interface.

Both classes then implement this interface and the Generic just applies to the the interface as the type of its input parameter.

Dragonthoughts
  • 2,180
  • 8
  • 25
  • 28