How to understand jathe New and this.something keyword

I hope I am allowed to post this question but I am having difficulty understanding the New keyword and this.
For example this,question = question and Dog Rottweiler = new Dog;

What would be a better way to understand it?

Thank you.

Hm, there’s a lot of angles to go about this so it’s hard to know which way will be easier.

Here’s one way to think of it:
When the operator new is used, like with new Dog(‘Rottweiler’), you are telling the computer:

Hey computer, I want to make a new copy of my Dog class, please allocate some new memory for this class with information about Rottweiler and save it to my variable rottweiler.

So now say the computer puts information about Dog(‘Rotweiller’) at memory location 1028 (just making up a number). Any time you do things that are about that specific dog (rottweiler), it will look in memory address 1028 to see what the data is.

Later you might say

Hey computer, I want to make a new copy of my Dog class, please allocate some new memory for this class with information about GermanShepherd and save it to my variable shepherd.

Now the computer might go to address 32768 (again, picking a random power of 2 here), and store information about GermanShepherd.

So now you have two different locations in memory with two different pieces of information about some Dog. But your code for class Dog is the same.

So for the this keyword, whenever you say to the computer,

I want to do something with my shepherd

The computer will call the class Dog code, and when this is used, it means the address for that specific dog. So this.name for shepherd will be at address 32768 and that’s where the computer will look (remember this.name for rottweiler will be at 1028)

1 Like