![](/img/trans.png)
[英]Should the constructor of a private inner class be declared public or private?
[英]java inner class private constructor, public members
我想知道这是否是设计课程的首选方式; 如果不是它有什么问题,什么是更好的选择?
class Calculator {
public Calculator(Input input) {...};
CalculatorOutput output;
class CalculatorOutput {
private CalculatorOutput() {} //private constructor - so no one other than Calculator can instantiate this class
Double someCalcStuff;
List<Double> someOtherCalcStuff;
}
public void calculate() {
CalculatorOutput op = new CalculatorOutput();
//..after this function populates the someCalcStuff & someOtherCalcStuff; it just returns an instance of CalculatorOutput
}
...
return op;
}
//usage
Calculator.CalculatorOutput result = new Calculator(input).calculate();
for (Double d: result.someOtherCalcStuff) {...}
我将CalculatorOutput作为计算器的内部类的原因是b / c除了返回计算器的输出之外没有其他目的或上下文。 我有CalculatorOutput的成员作为公共b / c我真的没有看到将它们设为私有的点,然后通过getter / setter访问...因为我不希望这个内部类被继承,或做任何其他这篇文章中提到的功能: 为什么要使用getter和setter?
用户无法实例化内部类(私有构造函数),因此我没有看到创建内部类的公共可访问成员(CalculatorOutput)的真正缺点
具体问题:
为了使代码更清晰,我要做的是创建一个Calculator包并将以下类添加到该包中:
我会做出以下更改:(将成员设为私有,并在需要时提供getter和setter)
class Calculator {
private CalculatorOutput output;
public Calculator(Input input) {/* logic here */}
// getters and setters
}
class CalculatorOutput {
private Double someCalcStuff;
private List<Double> someOtherCalcStuff;
// getters and setters
CalculatorOutput() {}
}
public class Test{
public static void main(String [] args)
{
Calculator calc = new Calculator();
CalculatorOutput output = new CalculatorOutput();
// use methods as needed
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.