开发者

calling Overloaded method from a generic method

开发者 https://www.devze.com 2022-12-24 04:20 出处:网络
How to create a generic method which can call overloaded methods? I tried but it gives a compilation error.

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);
   }
  }
 }

}    


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号