Overloading is fine. But if we consider that we have got two objects ObjectA and objectB. Both have got "id" and "name" variable. I would like to write a method (in third class), which returns the name of the given object. Writing overloaded function make me repeating the code. Is it a fine practice? Wouldn't be better to use generic functions instead?
So, I know I can write an overloaded function, sth. like that:
public String getInfo(ObjectA o){
if(o.getId()!=1) return o.name;
return "";
}
public String getInfo(ObjectB o){
if(o.getId()!=1) return o.name;
return "";
}
And it works fine. But both functions are identical! The only difference is the fact, they need an argument of the different type. Because they look the same, isn't it violating the DRY rule? I tried to write simple generic method, but IDE is marking that.getId and that.name() as an error and recommend casting it as ((ObjectA) that).getId() or ((ObjectB) that).getId(). Haven't I done it in the line" T that = clazz.cast(o);? What I am doing wrong?
public <T> String getInfo(Class<T> clazz, Object o) {
T that = clazz.cast(o);
if (that.getId()!=1) return that.name;
return "";
}
Generally I would like to know, if my idea is possible. How can i fix my error? And what is more, is it a good idea? Or is it better to simply write overloaded functions?
T
is erased toObject
, the above won't compile, sinceObject.getId()
is not an actual method. As others have suggested, you'd need to have a common interface on whichgetId
is defined. – Andy Turner Aug 21 '15 at 12:11T
isObject
. The consequences of erasure are only experienced at runtime (and in some degenerate cases at compile time, but only due to the specific twist on erasure in Java). – Marko Topolnik Aug 21 '15 at 12:32ObjectB
's requirements change, and its name gets split up intofirstName
andlastName
? What will happen to the interface andObjectA
? – nhaarman Aug 21 '15 at 17:42