简体   繁体   English

创建对象并在构造函数中使用它

[英]Creating an Object and Using it in a Constructor

Say we have a class called Maze . 假设我们有一堂课叫做Maze Now suppose that we have another class called MazeSolver . 现在假设我们还有另一个名为MazeSolver类。 So in order to create the Maze object in MazeSolver for the reason of using the methods from Maze, we create private Maze maze . 因此,为了使用Maze中的方法在MazeSolver创建Maze对象,我们创建了private Maze maze Then within the constructor of MazeSolver , we also write public MazeSolver(Maze maze) . 然后在MazeSolver的构造函数中,我们还编写了public MazeSolver(Maze maze) My question is, why do we have to do both? 我的问题是,为什么我们必须同时做这两项? What is the philosophy behind the idea? 这个想法背后的哲学是什么? Why can't we do one or the other opposed to doing both is I guess where I am confused. 我们为什么不能做一个或两个都不做,我猜我很困惑。

Well there is the field/variable where the Maze reference is stored: 那么,存在迷宫参考存储的字段/变量:

private Maze maze;

And there is the constructor where the Maze reference is passed and set 并有一个传递迷宫引用并进行设置的构造函数

public MazeSolver(Maze maze) { this.maze = maze; }

Beyond that, you need to ask a more specific question. 除此之外,您需要提出一个更具体的问题。

Here you have two options first one is you can use like this 在这里,您有两个选择,第一个是可以像这样使用

public MazeSolver(Maze maze) { 
this.maze = maze; 
}

second option is 第二个选择是

public MazeSolver() { 
maze = new maza();; 
}

Actually your requirement is you need to use maza behavior so in that case you need one instance of maza class( if those method are non-static). 实际上,您的要求是您需要使用maza行为,因此在这种情况下,您需要一个maza类的实例(如果这些方法是非静态的)。 that's why you need to initialize or you assign object to maza 这就是为什么您需要初始化或将对象分配给maza的原因

I hope this will help you to understand your requirement 我希望这可以帮助您了解您的要求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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