I want to create an interface that allows any implementation class like this:
public interface MyInterface
{
void doSomething( <A extends MyBaseClass> arg1);
}
public class MyImpl implements MyInterface
{
void doSomething ( SomeClassExtendsMyBaseClass arg1)
{
// do something
// SomeClassExtendsMyBaseClass is a class that extends MyBaseClass
}
}
I get a syntax error when doing the above. Can someone show me how to accomplish this goal?
Thanks
We can subtype a generic class or interface by extending or implementing it.
It is the mechanism in java by which one class is allowed to inherit the features(fields and methods) of another class. Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body).
By interface, we can support the functionality of multiple inheritance. It can be used to achieve loose coupling.
Generic Interfaces in Java are the interfaces that deal with abstract data types. Interface help in the independent manipulation of java collections from representation details. They are used to achieving multiple inheritance in java forming hierarchies. They differ from the java class.
public interface MyInterface<A extends MyBaseClass>
{
void doSomething(A arg1);
}
public class MyImpl implements MyInterface<SomeClassExtendsMyBaseClass>
{
public void doSomething ( SomeClassExtendsMyBaseClass arg1)
{
// do something
// SomeClassExtendsMyBaseClass is a class that extends MyBaseClass
}
}
@salexander has the solution, but the reason you have to do this is that your derived class is trying to be more specific which you cannot do. The reason is as follows.
MyInterface mi = new MyImpl();
mi.doSomething(new MyOtherClassWhichExtendsMyBaseClass());
In the interface you said you can take ANY MyBaseClass, so you have to honour that.
In @salexander's solution the code would look like.
MyInterface<SomeClassExtendsMyBaseClass> mi = new MyImpl();
mi.doSomething(new MyOtherClassWhichExtendsMyBaseClass()); // compile error.
it should be
<T extends MyBaseClass> void doSomething(T arg1);
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