Let's say I have the folowing:
List<Apple> myList = new ArrayList<Apple>();
And if I want to call myList.add(myApple)
, Java expects from myApple
to have type of Apple
, not any others (except subclasses of course). But what if I want to have an object (Blender
) and have different method signatures according to type declared inside <>
and without method overloadings; like so:
Blender<Apple> Tool = new Blender<Apple>();
Tool.blendIt(new Apple()); //expects to have only apples in here
Blender<Banana> OtherTool = new Blender<Banana>();
OtherTool.blendIt(new Banana()); //only Banana's are permitted
Is it possible?
you are looking for Generic Class.
class Blender<T>{
T t;
public void blendIt(T arg){
//stuff
}
}
class Test {
public void method() {
Blender<Apple> blendedApple = new Blender<Apple>();
blendedApple.blendIt(new Apple());
Blender<Bannana> blendedBannana = new Blender<Bannana>();
blendedBannana.blendIt(new Bannana());
}
}
Yes it is:
public class Blender<T> {
public void blendIt(T arg) { ... }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With