tags:

views:

66

answers:

1

How to create a generic method which can call overloaded methods? I tried but it gives a compilation error.

Test.java:19: incompatible types found : java.lang.Object required: T T newt = getCloneOf(t); ^

import java.util.*;

public class Test {


 private Object getCloneOf(Object s) {
  return new Object();
 }

 private String getCloneOf(String s) {
  return new String(s);
 }

 private <T> Set<T> getCloneOf(Set<T> set){
  Set<T> newSet = null;
  if( null != set) {
   newSet = new HashSet<T>();
   for (T t : set) {
    T newt = getCloneOf(t);
    newSet.add(newt);
   }
  }
 }

}    
+3  A: 

A T variable can only be set equal to an object of class T, or one of it's subclasses. In your case, getCloneOf() is returning an Object, which isn't going to be a subclass of T, or even necessarily what T is.

For example:

class Parent {
    public void doStuff(){
    }
}

class Child extends Parent {
    public void doDifferentStuff(){
    }
}

This is okay:

Parent p = new Child();  

Because this will work even if p is a Child class object, because it inherited that function from Parent:

p.doStuff(); 

This is not okay:

Child c = new Parent();

Because this should theoretically work because the variable is of type Child, but were the previous line allowed this would blow up because a Parent object doesn't have a function with that name.

c.doDifferentStuff();
Matt Blaine