我在下面定义了两个类:
public class junk {
private BigInteger a = BigIngeger.valueOf(1), b=BigInteger.valueOf(2), c;
public void DoSomething() {
c = a.add(b);
}
// ... other stuff here
}
public class junkChild extends junk {
private BigDecimal a = BigDecimal.valueOf(1), b=BigDecimal.valueOf(2), c;
// I want a, b, c to override the original BigInteger a,b,c
// ... other stuff here
}
public class myClass {
public static void main(String args[]) {
junk a1 = new junkChild();
a1.DoSomething();
}
}
不幸的是,上述方法无效.
我想要做的是简单地将a,b,c更改为junkChild中的BigDecimal,而无需再次重写DoSomething().即使我必须再次编写它,代码也会完全相同,所以应该有一种方法可以让它无需编写即可完成. DoSomething函数应该检查类型a1是否具有正确输入和返回类型的add方法,如果是,则调用它而不用担心a,b,c是什么类型.
可以这样做吗?
解决方法:
不,你不能这样做 – 至少在编译时不行.这两种添加方法实际上是无关的 – 它们不是来自界面或类似的东西.
你可以用反射来做(在为a,b和c或类似的东西添加属性之后 – 字段不能像这样被“覆盖”),但它不会非常好.
标签:anonymous,java,class,overloading,field
来源: https://codeday.me/bug/20190724/1519289.html