java - 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 类继承自LinearLayout
C 类的功能。而 B 类继承自 C 类Preference
的相同功能。
我知道interfaces
可以default
实现,但它要求Java 1.8 and above
不适合我。
任何帮助都感激不尽!
解决方案
不幸的是它有可能实现。一个类不能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
初始化期间将其简单地初始化为匿名类。
推荐阅读
- android - 库模块不包含 Android 中的依赖项
- python - 如何检测字符串中的浮点数并将其转换为单个整数
- ibm-midrange - 如何更改 iSeries Admin2 JAVA_HOME 环境变量
- json - 从 Hive 访问大型嵌套 JSON 数据集
- android - 'json 响应以 '/' 字符开头是什么意思?
- c# - 创建一个抽象函数,该函数根据继承者采用不同的参数
- mysql - Ejabberd MySQL 模式
- csv -  或 ? 使用骆驼从 s3 读取 csv 文件时,字符被添加到第一列
- excel - 如何根据其他列的颜色更改列的颜色?
- mysql - 如何解决 CentOS 8 中的这个 Mysql2 gem 错误?