我有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&amp; 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继承自Preference
,具有相同的C类功能。
我知道可以interfaces
实施的default
,但它需要Java 1.8 and above
不适合我。
非常感谢任何帮助!
答案 0 :(得分:0)
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
,并且在初始化期间只需将其初始化为匿名类。