Welcome to the Treehouse Community
Looking to learn something new?
Holly Fox2,808 Points
What's the significance of creating a "new" object in java?
I'm very new to coding and just currently understanding the principles of Java on the android track.
The rules of initialising, variables, importing and finding ID's between the packages are starting to click into place. The part I'm still struggling to grasp is creating "new" objects. Please could someone explain why we do this?
Thank you Holly
Welcome to the world of programming.
Well to put it in easy words, new allocates space for an object.
So from the concepts that you already know, for example I have a class called Hello and a some methods inside it. Now I need to define an object of Hello to be used in some other class. For that we usually write
here ha can be any user defined name.
So did this create an object?
NO. This statement simply tells us that ha is of type Hello. But, by convention ha does not exists as yet.
However, when I write
Hello ha = new Hello();
now ha has physical existence within the memory, or what we call program stack. Thus, the keyword new has alloted ha some space in memory so that we can now use it.
Hope this explains :)
A great thing about Objects is that they can hold their information and set of properties which make them awesome to use in a program. Often I feel the best way to explain things like this are through examples. So, in this example I am the owner of an animal farm.
String name; int age; String gender; Animal zebra = new Animal(); //Here I am creating a new Animal object called 'zebra'. zebra.name = "Martin"; //Here I am giving the zebra object a name using the string we defined earlier on in this code. System.out.println("The Zebra at this Zoo is called" + zebra.name);
I hope that this helps you understand objects a bit more. If you still need any more help then please feel free to ask and I will try and help you as much as I possibly can.