Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Amrit Pandey
17,595 PointsDeclaring Instance of a class in other class! | JAVA
Hi I was wondering, what just happened in Hangman Game.
In Prompter.java we have declared game instance which was created in Hangman.java.
Alright so I am confused as to why it was necessary to declare game instance using Game as datatype. Both Prompter and Game had their instances already in Hangman.java.
Hangman.java ======>
public class Hangman{
public static void main(String[] args){
Game game = new Game("treehouse");
Prompter prompter = new Prompter(game);
boolean isHit = prompter.promptForGuess();
if(isHit){
System.out.println("We got a hit!");
}else{
System.out.println("Oops Missed!");
}
}
}
Prompter.java ======>
import java.util.Scanner;
class Prompter{
private Game game;
public Prompter(Game game){
this.game = game;
}
public boolean promptForGuess(){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a letter: ");
String guessInput = scanner.nextLine();
char guess = guessInput.charAt(0);
return game.applyGuess(guess);
}
}
TL;DR I am not able to understand meaning of this line
private Game game;
in Prompter.java
1 Answer
Rohit Sai Teja Gadu
619 PointsHey Amrit, we are using Game class in Prompter class, so we are declaring "private Game game" so that we can use game as an instance(object) of class Game in Prompter class (check Prompter class constructor: public Prompter(Game game))
Amrit Pandey
17,595 PointsAmrit Pandey
17,595 PointsSo as I know, to declare an instance of a class we do it by
Game myGame = new Game(), The way we declare the instance of Game in Promppter is simplypublic Game gamejust like we do with the private variables!