Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic class that extends class and implements interface

To reduce dependece of class, I want to send parameter (using generic class) to constructor that extends some class and implements interface, for example

public interface SomeInterface{     public void someMethod(); }  public class MyFragment extends Fragment implements SomeInterface{     //implementation }  //here is classs, that I need to create. T must extend Fragment and implements  //SomeInterface. But, I'm afraid, if I'll use MyFragment directly, it will create a //dependence of SomeClass from MyFragment.  public class SomeClass /*generic?*/ {     public SomeClass(T parent); } 

Is it possible?

Futher, using my T class, I want to create views, using T.getActivity() as Context.

like image 885
Dmitry Zaytsev Avatar asked Jan 15 '12 16:01

Dmitry Zaytsev


People also ask

Can a generic class extend an interface?

Java Generic Classes and SubtypingWe can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.

Can you extend a class and implement an interface?

A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.

Can a generic class implement an interface?

Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.

What is a class that implements an interface called?

"Interface implementation" is generalised while in android we usually call it "Interface Listener class". In your case if A implements interface B then it will also implement its methods.


1 Answers

T must extend Fragment and implement SomeInterface

In that case you could declare SomeClass as the following:

public class SomeClass<T extends Fragment & SomeInterface> 

That would require an object of type T to both extend Fragment and implement SomeInterface.

Further, using my T class, I want to create views, using T.getActivity() as Context.

I'm unfamiliar with Android, but if getActivity() is a public instance method declared in Fragment then will be entirely possible to call it on an instance of T, since the compiler will know all Ts must inherit that method.

like image 117
Paul Bellora Avatar answered Sep 26 '22 02:09

Paul Bellora