首页 > 解决方案 > Android - 扩展泛型类

问题描述

我有 2 个类(A 和 B)从基本抽象类(C)继承。这个父类 (C) 为其两个子类 (A & B) 实现了一些通用功能,并且必须从不同的类继承。所以,我决定做generic一个。但我不知道这是否可能以及如何去做。看看我下面的代码:

父类:

//THIS PARENT CLASS MUST BE GENERIC TO EXTEND DIFFERENT CLASSES 
//SUCH AS Preference and LinearLayout
abstract class C<T> {

public C(Context context) {
    super(context);
}

public C(Context context, AttributeSet attrs) {
    super(context, attrs);      
}

public C(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

int commonFunc1(WebView view, int mode){
    //implementation
}

//lots of common functions

}

Preference 和 LinearLayout 具有相同的构造函数。

A & B 类:

//Class A must be inherited from the base class C that is inherited from LinearLayout
public class A extends C<LinearLayout>{

public A(Context context) {
    super(context);
}

public A(Context context, AttributeSet attrs) {
    super(context, attrs);      
}

public A(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

void exec(){
  commonFunc1(myWebView, 1);
}

}

//Class B must be inherited from the base class C that is inherited from Preference
public class B extends C<Preference>{

public B(Context context) {
    super(context);
}

public B(Context context, AttributeSet attrs) {
    super(context, attrs);      
}

public B(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

void exec(){
  commonFunc1(myWebView, 2);
}

}

所以,我的目标是让 A 类继承自LinearLayoutC 类的功能。而 B 类继承自 C 类Preference的相同功能。

我知道interfaces可以default实现,但它要求Java 1.8 and above不适合我。

任何帮助都感激不尽!

标签: javaandroidgenericsinheritance

解决方案


不幸的是它有可能实现。一个类不能T只扩展泛型类型。您可以使用组合,而不是尝试使用某些泛型类型实现继承。

您可以执行以下操作:

class A extends LinearLayout {

    ...

    ...
    // If C is expensive to create:
    private final C cObj;
    public A(final C cobj){
        this.cObj = cObj;
    }

    //If C needs to be created based on A then you can pass all the parameters needed for C as parameter for A's contructor

    void exec(){
        c.commonFunc1(myWebView, 2);
    }
}

class B extends Preference {

    ...
    private C c;
    ...
    //Use common functions of class C where-ever needed.

}

如果需要将其class C设为抽象以便可以更改某些特定输入,那么您仍然可以class Cabstract初始化期间将其简单地初始化为匿名类。


推荐阅读