Sep 13, 2013

How to create an Object in Java

How to create an Object in Java: Creating Object is very important step to execute our java program successfully. As we know we can call all non-static members only after creating object of the class so must need to create an object. We can execute non-static block without creating object below java5 version. In this post we will know how to create an object in java. Object is an instance variable of the class and it can be created by using "new" keyword.

"new" keyword is responsible for allocating memory to the object. Code to create an object is as follows-

Example-

new Java_program();
new Java_example();
new Test();

In above example we are creating an object by using new keyword. "new" kyword is allocating memory to the object anf returning reference of the object. This reference is needed to access the non-static members of the class so we have to store in a variable called a reference variable.

Example-


Java_program ob=new Java_program();

Here, ob is the reference variable which stores the referenece of the object. We can access non-static members using "ob"  as follows-
Example-

class Java_program
 {
   int a=10,b=5;
   void mul()
    {
       System.out.println("Multiplication is="+a*b);
    }
  public static void main(String argxyz[])
    {
      Java_program ob=new Java_program();
      ob.mul();
    }
 }