user3092043
user3092043

Reputation: 49

Creating an Object and Using it in a Constructor

Say we have a class called Maze. Now suppose that we have another class called 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. Then within the constructor of MazeSolver, we also write 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.

Upvotes: 0

Views: 137

Answers (2)

Pankaj Goyal
Pankaj Goyal

Reputation: 980

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). that's why you need to initialize or you assign object to maza

I hope this will help you to understand your requirement

Upvotes: 0

user2684301
user2684301

Reputation: 2620

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.

Upvotes: 4

Related Questions