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

C# C# Objects Loops and Final Touches Playing the Game

How does "new MapLocation(1, 3, map)" works?

Why not MapLocation ml = new MapLocation(1, 3, map)? What is the difference? How does it work? Does it store in a memory? Can I operate MapLocation without an instance? What is that? Is instance is created? Does it live its own life? So many questions, I am sorry but I just didn't get it.

5 Answers

Steven Parker
Steven Parker
231,198 Points

I see it passed as a parameter when creating a tower:

                    new Tower(new MapLocation(1, 3, map)),

This causes it to be stored in the variable "_location" inside the "Tower" object, which will have private access to it. This fulfills the design principle known as "encapsulation", since no other part of the program needs to have access to it.

Steven Parker
Steven Parker
231,198 Points

I don't understand the question "Why not MapLocation ml = new MapLocation(1, 3, map)?". What are you comparing that to when you say "Why not"?

But the "new" operator creates a new instance. And the only operations you can perform on a class without an instance are the ones that are declared "static". The "MapLocation" class has no static components so you must create an instance to use it.

Why not means why we should use "new MapLocation" instead of using "MapLocation ml = new MapLocation(1, 3, map)". Isn't it better to have own instance and access it through a variable? Ok, it just lives its own life. I can't access it. It just lives.

Steven Parker
Steven Parker
231,198 Points

Where do you see "new MapLocation" written by itself?

In the C# course file Game.cs as I remember.

Thank you, Steven! I asked this question because I have red about threads and just strange idea come to my mind. Is it possible to make a living code where you initialize one thread than another and there are loops in threads and it just communicates with each other and lives its own life? Kind of living code. Never mind. It just scared me a little when I started learning Java and I thought about extremely complex Java API. And I was dreamt of reading a code that Java is written on to get an idea how it's all working but turns out that things are simpler than I expect. Just my fears because of lack of understanding. Thank you again!