简体   繁体   English

java内部类私有构造函数,public成员

[英]java inner class private constructor, public members

I'd like to know if this is the preferred way to design a class; 我想知道这是否是设计课程的首选方式; if not what's wrong with it and what's a better option? 如果不是它有什么问题,什么是更好的选择?

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) {...}

The reason I have CalculatorOutput as an inner class of Calculator is b/c it's got no other purpose or context than returning the calculator's output. 我将CalculatorOutput作为计算器的内部类的原因是b / c除了返回计算器的输出之外没有其他目的或上下文。 I have CalculatorOutput's members as public b/c I don't really see a point in making them private , and then accessible via a getter/setter...Since I don't expect this inner class to be inherited, or do any other functionality mentioned in this post: Why use getters and setters? 我有CalculatorOutput的成员作为公共b / c我真的没有看到将它们设为私有的点,然后通过getter / setter访问...因为我不希望这个内部类被继承,或做任何其他这篇文章中提到的功能: 为什么要使用getter和setter?

The user cannot instantiate the inner class (private constructor), so I don't see a real drawback in creating public accessible members of the inner class (CalculatorOutput) 用户无法实例化内部类(私有构造函数),因此我没有看到创建内部类的公共可访问成员(CalculatorOutput)的真正缺点

Specific questions: 具体问题:

  • Is this approach bad? 这种做法不好吗? why? 为什么?
  • What's a better approach to achieve this? 有什么更好的方法来实现这一目标?

To make the code cleaner, what I would do is create a Calculator package and add the following classes into that package: 为了使代码更清晰,我要做的是创建一个Calculator包并将以下类添加到该包中:

  1. Calculator 计算器
  2. CalculatorOutput CalculatorOutput

And I would make the following changes: (make members private and provide getters and setters where needed) 我会做出以下更改:(将成员设为私有,并在需要时提供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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM