Scientech Easy How to create object in Java with example & programs | Scientech Easy

Monday, April 8, 2019

How to create object in Java with example & programs

In this tutorial, we will learn How to create an object in Java with a simple example and programs which will be helpful to understand the concept of creating an object in Java. Can you think why we need to create an object in Java programs? Let's see first understand it.

For which purpose we create an object in Java


We create an object in Java applications because of three reasons. They are as follows:
1. Since Java is purely object-oriented programming language. So Everything is done in the form of objects only. Therefore, objects are required in the Java programming language.
2. To store data temporarily in Java application, we require to create an object. The object provides temporary storage for our data.
3. In Java, By creating an object, we can call the members of one class from another class. It is useful when we need to use common code in every class again and again.

4. To access members of any particular class, we have to create an object of the respective class. Whenever we create an object in any program, the Object reference variable is automatically generated. By using this object reference variable only, we can access the members of a particular class. 
The reference variable must have reference value. The Dot(.) operator gives you to access an object's state and behavior (instance variables and methods).  These are the reasons for which we create objects in Java programs.   

How many ways to create object in Java?


There are several ways to create an object of a class in Java. They are as follows.
1. Using the new keyword
2. Using Class.forName
3. Using Clone.
4. Using Object Deserialization.
5. Using ClassLoader.
In this chapter, we will learn using the new keyword to create an object of the class and another way we will learn one by one in the next tutorial.

What is a new operator in Java?


In Java, a new operator is a special keyword which is used to create an object of the class. It allocates the memory to store an object during runtime and returns a reference to it. This reference is the address of the object in the heap memory allocated by the new operator. This reference (memory address) is then stored in a variable called object reference variable that can be accessed from anywhere in the application. See below image.

How to create object in Java


In Java, an object of a class is created using the new keyword in three steps. They are as follows.
1. Declaration of a reference variable.
2. Creation of an object.
3. Linking the object and the reference variable.

Declaration of a reference variable


A general form of declaration of a reference variable is given below.
      Classname  object_reference_variable; // Creating a reference.
The Classname is the name of the class which is being instantiated. The object reference variable is a variable of type Classname.
For example, consider a class whose name is College and object reference variable myCollege. It can be declared like this.
        College myCollege;
This statement tells the JVM to allocate memory space for a reference variable and names that reference variable myCollege. The reference variable is of type College.

Creation of an object


We can create an object in general form like this.
     new Classname();
The class name followed by parentheses represents the constructor of the class.
For example,
       new College();
This statement tells the JVM to allocate memory space for a new College object on the heap. 

Linking object and reference


Now, we will link the object and reference created above like this. 
  Classname object_reference_variable=new Classname();
Assigns the new College to the reference variable myCollege.
   College myCollege=new College(); 
where 
      College Name of the class.
      myCollege     Object reference variable which stores the address of the object in the stack memory.
      new      keyword that stores the object in the heap memory.
  College() Constructor of the class.
        =         The equal sign(=) is an assignment operator. It simply says to take the object created by new keyword and assign it to the object reference variable.
Let's understand the memory allocation for storing an object in Java.
How to create object in Java.
Explanation: 
When the statement College myCollege=new College(); will be executed by JVM, an object will be created in the heap memory and stores the data "Hello Java" in it. The address of the object is stored in the reference variable myCollege in the stack memory. 
Key points: 
Remember that creating an object means allocating memory for storing data.
You can also create an object of the class in two steps like this.
Step 1: College myCollege; // Declaration of reference to the object.
Step 2: myCollege=new College(); // Creating an object.

 Creating multiple objects of one type:
   College myCollege1=new College();
   College myCollege2=new College();
Both reference variables have different memory addresses.
Creating the object with passing different parameters to the constructor:
    Student st=new Student(); // It will call default constructor.
    School sc=new School("DEEP"); // It will call Parameterized constructor.
Let's see a very simple program step by step to understand the concept. 
Program Source Code 1: 
    package scientecheasy; // Step 1: Create a class with the name HelloJava. public class HelloJava { // Step 2: Declare the constructor with the class name. This constructor is a default. HelloJava(){ // It will print the message on the console. System.out.println("Hello Java"); } // Step 3: Declare a method and Print any message which you want. void display(){ System.out.println("Welcome to online Java tutorial point. "); } // Step 4: Declare the main method to start the execution of program. This method is static. public static void main(String[] args) { // Step 5: Create an object of the class with the object reference variable 'obj'. HelloJava obj=new HelloJava(); // It will call default constructor as object created. // Step 6: Now call the method to print the output on the console using object reference variable 'obj'. obj.display(); } }

    Output: Hello Java Welcome to online Java tutorial point.
You follow all the above steps to make your program easy and keep all steps in mind. 

What is System.out.println()?


1. System is a class which is predefined by Sun Microsystem.
2. out is a variable declared in System class of type PrintStream.
3. println is a method defined in PrintStream class.

What is the void?


The void is a keyword which indicates that this method does not provide or return any data back to the class of an object.
Now let's take one more example for practice.
Program source code 2: In this program, we will calculate the sum of two numbers. you follow all the above steps.
    package scientecheasy; public class Sum { // Declare instance variables. int a; int b; // Declare a default constructor and initialize the value of variables. You can also initialize directly to the variables. This is another way to initialize the value of variables. Sum(){ a=50; b=20; } // Declare a method and write the logic to add the numbers. void display(){ int sum=a+b; System.out.println("Sum of two numbers: " +sum ); } public static void main(String[] args) { // Create an object of the class and call the method using reference variables to print output on the console. Sum sm=new Sum(); sm.display(); } }
    Output: 70
If you are a beginner and unable to understand this program then you go for the next tutorial. You can easily understand after the next tutorial.

Final words
We hope that this article has covered all the important topics related to How to create an object in Java for example and programs. Hope that you will have enjoyed this article. We always try to understand you in an easy way. 
Thanks for reading!
Next ➤ Object Declaration and Initialization

⏪ Prev Next ⏩