Welcome back to Java Code Online. Creating of Objects is a very easy thing, if you understand the actual processing going on at the back end. Understanding how to create a new Object is essential for getting a good hold on the Principle of OOPS and Java itself.
For creating a new Object in Java, we use the keyword "new". Simple isn't it. For illustrating this concept, we create a class called BMW, and then make a new Object of this class in a new class called TestDrive. Here we will step by step understand the steps involved in creation of a new Object and its importance on the heap. Oh! I forget to tell you, every Object in Java lives on the heap. Every time you create a new Object it takes some space on the heap, which must be cleared once the Object gets useless or out of reach. For this we use Garbage Collection in Java.
Anyhow, here is your first class.
System.out.println("Speed is 100 miles/hr");
Public Static void main(String args)
BMW b = new BMW();
b.color = "red";
The above class TestDrive when runs, it prints the output as "Speed is 100 miles/hr". In the above program, we have created a class called BMW and in that defined its instance variables and methods. Then we have defined a seprate class called TestDrive in which we make an Object of type BMW, we set the color of this BMW to red, and then we call the showSpeed() method, which displays the speed of the BMW.
Here the "." operator in b.showSpeed() is used for calling the showSpeed function of the BMW. The main thing here is that we have created a new Object by using the keyword "new".
When we say:-
BMW b = new BMW();
Here there are three steps involved, they are:-
1. Declaration of a reference variable
2. Creation of an Object
3. Assignment of the new Object to the refernce variable.
I hope you got my point. Anyhow I will explain it again. When we say:-
we have just created a new refernve variable of type BMW. And then we say:-
here we have just created a new Object of type BMW. And then we equate them by using the "=" operator.
So now, we have created a new Object and then assigned it a reference variable, and we have done this because now we can use this reference variable to perform operations on this Object.
Now I am pretty sure that you have got my point. In case you like my article, do leave me a comment. For more information on Java, keep buzzing Java Code Online.