【问题标题】:Android - extends generic classAndroid - 扩展泛型类
【发布时间】:2018-11-26 09:17:29
【问题描述】:

我有 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);
}

}

所以,我的目标是让从LinearLayout 继承的 A 类具有 C 类的功能。而从 Preference 继承的 B 类具有与 C 类相同的功能。

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

任何帮助将不胜感激!

【问题讨论】:

  • 您的措辞确实不清楚。您不会从不同的类继承。扩展泛型类时,您可以指定或不指定泛型类型参数。这并不意味着您从该类型参数类继承任何东西。
  • @GhostCat,是否可以分别从A类和B类中指定C类的祖先类
  • 不,不是。 C 扩展对象。故事结局。看来你应该更深入地研究泛型。
  • @GhostCat,这就是我问这个问题的原因。在我的情况下,我需要复制 A 类和 B 类的代码?还是有更好的解决方案?
  • 我想知道对于像 LinearLayoutPreference 这样完全不相关的类,您可以拥有哪些“常用功能”

标签: java android generics inheritance


【解决方案1】:

不幸的是,它有可能实现。类不能仅扩展通用类型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 C 设为abstract,并且在初始化期间只需将其初始化为匿名类。

【讨论】:

  • 很不方便,因为我要向C类的函数传递很多变量
  • @Nolesh 您仍然可以将这些参数传递给 A 和 B 的构造函数,以便可以初始化 C。无论如何,您需要为构造 C 做些什么。您还可以先初始化 C 并将 C 的对象传递给 A & B
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多