Say I have an abstract base class that has a method to generate Foo objects (acting like a factory method). Right now my classes look something like this:
public class Foo
{
}
public class FooBar extends Foo
{
}
public abstract class MyBaseClass
{
abstract public Foo createObject();
}
public class MyDerivedClass extends MyBaseClass
{
@Override
public Foo createObject()
{
return new FooBar();
}
}
This is sub-optimal, because code calling MyBaseClass#createObject needs to cast the return value back to what it was originally, i.e.:
FooBar fooBar = (FooBar)myDerivedClass.createObject();
This is like taking my pants off to put them on again.
I haven’t used Java generics for a while, but I was hoping I could turn that abstract method into a templated method, something like:
public abstract class MyBaseClass
{
abstract public <T extends Foo> T createObject();
}
But I get the following errors from Eclipse when I try to implement the method in the derived class:
public class MyDerivedClass extends MyBaseClass
{
@Override
public <FooBar extends Foo> FooBar createObject() // The type parameter FooBar is hiding the type FooBar
{
return new FooBar(); // Cannot instantiate the type FooBar
}
}
I don’t think I’m applying the right solution to my problem of reducing the unnecessary casting going on. Any ideas?
This is with Java 1.6.
You’re probably looking for a generic class (as opposed to a generic method):
To learn more about Java generics, I highly suggest you read the Generics tutorial.