Blog is under construction. Blog is under construction.

Wednesday, 8 August 2012

What are the other ways to create an object other than creating as new object?


Q: How to create an object? What are the other ways to create an object other than creating as new object?
Answer:

Creating an Object:

As mentioned previously a class provides the blueprints for objects. So basically an object is created from a class. In java the new key word is used to create new objects.
There are three steps when creating an object from a class:
·         Declaration . A variable declaration with a variable name with an object type.
·         Instantiation . The 'new' key word is used to create the object.
·         Initialization . The 'new' keyword is followed by a call o a constructor. This call initializes the new object.
Example of creating an object is given below:


class Puppy{
   public Puppy(String name){
      // This constructor has one parameter, name.
      System.out.println("Passed Name is :" + name ); 
   }
   public static void main(String []args){
      // Following statement would create an object myPuppy
      Puppy myPuppy = new Puppy( "tommy" );
   }
}

Passed Name is :tommy
If we compile and run the above program then it would produce following result:

Different ways of creating object in java:
There are different ways to create objects in java:

1) Using new keyword
This is the most common way to create an object in java.
MyObject object = new MyObject();

2) Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way. It is also known as reflection.
 MyObject object = (MyObject)Class.forName(“com.abc.MyObject”). newInstance();

3) Using clone()
The clone() can be used to create a copy of an existing object.
 MyObject anotherObject = new MyObject();
 MyObject object = anotherObject.clone();

4) Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();

5) Using reflection in another way.
this.getClass().getClassLoader().loadClass(“com.abc.myobject”).newInstance();

Q: What is the difference between instance, object, reference and a class?
Answer:
Class: A class is a user defined data type with set of data members & member functions
Object: An Object is an instance of a class
Reference: A reference is just like a pointer pointing to an object
Instance: This represents the values of data members of a class at a particular time

0 comments:

Post a Comment