【发布时间】: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 类的代码?还是有更好的解决方案?
-
我想知道对于像
LinearLayout和Preference这样完全不相关的类,您可以拥有哪些“常用功能”
标签: java android generics inheritance