【发布时间】:2018-01-31 05:21:00
【问题描述】:
我有两节课 甲类: 具有4个不同数据类型的成员变量和3种方法(m1()、m2()和m3())
例如:
class ClassA
{
String a;
String b;
Double c;
UserDefinedTypeA d;
public m1(){
//All the 4 variables are used here.
}
public m2(){
//All the variables are used here.
}
public m3(){
//All the variables are used here.
}
B 类: 具有 4 个成员变量和 3 个方法(m1()、m2() 和 m3())。 其中三个成员变量与 ClassA 类型相同,只有第四个变量类型不同。
例如:
class ClassB
{
String a;
String b;
Double c;
UserDefinedTypeB d;
public m1(){
//All the 4 variables are used here.
}
public m2(){
//All the variables are used here.
}
public m3(){
//All the variables are used here.
}
现在我想避免在子类中覆盖 m1、m2 和 m3,因为类型 4 的成员变量不同。 作为一种解决方案,我计划在超类中创建另一个成员变量,其类型为:UserDefinedTypeB,并从子类构造函数初始化此变量。检查 UserDefinedTypeB 是否为 null 的所有方法。如果它不为 null,则 i 将执行子类特定逻辑,否则将继续使用支持 UserDefinedTypeB 的超类逻辑。
但是感觉这会降低性能。有关提出更好方法的任何建议。
【问题讨论】:
-
什么是子类,什么是超类?从你的问题中真的不清楚。在我看来,正确的解决方案可能涉及泛型——所以你可能有一个泛型超类
SuperClass<T>,其中ClassA extends SuperClass<UserDefineTypeA>和ClassB extends SuperClass<UserDefinedTypeB>包含所有常见功能。但我不能肯定地说,因为我不明白你想要达到什么目的。
标签: java overriding