如何从同一个类中的另一个构造函数调用抽象类的构造函数(方法重载)[重复]
Posted
技术标签:
【中文标题】如何从同一个类中的另一个构造函数调用抽象类的构造函数(方法重载)[重复]【英文标题】:How to call the constructor of an Abstract class from another constructor inside the same class (method overloading) [duplicate] 【发布时间】:2020-02-15 09:13:25 【问题描述】:我正在扩展我正在开发的一个类的 API,并希望使其向后兼容 - 这样它就不会破坏该类的任何现有用户。我通过向构造函数添加一个新参数来创建新功能。
为了不重复代码(我可以将旧构造函数中的代码复制粘贴到新构造函数中),我想更改现有构造函数以调用新构造函数,将 0 作为新参数的默认值传递,但我我收到编译错误,method call expected
。
我试图做的事情是不可能的(不支持方法重载?)还是遗漏了什么?
为了帮助说明我的意思,请看下面的简单示例,
public abstract class AbstractCalculator
int result;
// new parameter being added
public AbstractCalculator(int a, int b)
result = a + b;
// existing functionality
public AbstractCalculator(int a)
//compilation error here - Method call expected
AbstractCalculator(a, 0);
public class Calculator extends AbstractCalculator
public Calculator(int a)
super(a);
public static void main(String args [])
Calculator calc = new Calculator(4);
System.out.println(calc.getResult());
【问题讨论】:
AbstractCalculator(a, 0) 替换为 this(a, 0); 【参考方案1】:// existing functionality
public AbstractCalculator(int a)
this(a, 0);
【讨论】:
是的 - 谢谢。以上是关于如何从同一个类中的另一个构造函数调用抽象类的构造函数(方法重载)[重复]的主要内容,如果未能解决你的问题,请参考以下文章