Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java interface input argument extends from a base class

Tags:

java

generics

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

like image 349
Sean Nguyen Avatar asked Jan 05 '11 19:01

Sean Nguyen


People also ask

Can a generic class extend an interface?

We can subtype a generic class or interface by extending or implementing it.

What is interface inheritance?

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).

Does interface support multiple inheritance?

By interface, we can support the functionality of multiple inheritance. It can be used to achieve loose coupling.

What is a generic interface in java?

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.


3 Answers

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
   }
}
like image 52
salexander Avatar answered Oct 28 '22 02:10

salexander


@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.
like image 29
Peter Lawrey Avatar answered Oct 28 '22 02:10

Peter Lawrey


it should be

 <T extends MyBaseClass> void doSomething(T arg1);
like image 42
Nishant Avatar answered Oct 28 '22 00:10

Nishant