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 trialveronikapost
2,552 PointsInstance creation: console vs. luck
Hi Everyone! I find this small workshop about Java loops very helpful, so thank you for putting it together Treehouse and Craig. I have a question about the instance creation in our MiniGolf example. Here is the original code that Craig wrote:
Console console = System.console();
Random luck = new Random();
However, why the creation of console instance is so different? Why we are creating it through the System class, and not through the new keyword like this?:
Console console = new Console();
2 Answers
Craig Dennis
Treehouse TeacherExcellent question Veronika Post (and thanks for the tag Bob Allan !)
System.console()
is a static method that gets a hold of an already created console object. There is only one available (also known as a Singleton). Somewhere behind the scenes the System
class is using an instance that was created using the new
keyword.
However the System.console
static method returns that instance (if it exists).
veronikapost
2,552 PointsThank you very much, Craig Dennis and Bob Allan! I appreciate the help from you both. I did quite a lot of extra reading, and understood how static methods work, and also that I have to create a new console object using System.console() method, seems that I cannot do it through Console class constructor because the constructor is private. But can I ask you why there is no option of creating it through the constructor? I'm sure there is a reason for that, and I am probably running way to ahead of the current workshop, but I was just curious. Anyway, thank you both for your time.
Bob Allan
10,900 PointsBob Allan
10,900 PointsThat is a really great question Veronika Post, I would like to know the answer to that myself. It might help if we tag Craig Dennis, just to get his attention. :)