Tag Archives: Object Creation ways

Java: Object


Pre-Requisite: Java:Class
In the previous post, you learn about the Java Class declaration, implementation, and types of classes. Here we will discuss Object which is the basic unit of Object-Oriented paradigm to represent real-life entities.

When an instance of a class is created is known as Object. These instances share attributes and behaviors i.e methods of the class. These values of attributes will be unique for each object i.e called state.

A java program may have lots of objects and these objects interact with each other by invoking methods. An object consists of :

  • Identity: It gives a unique name to the identification of an object and enables one object to interact with other objects.
  • State: It is represented by attributes/properties values of an object.
  • Behavior: It is represented by methods of an object to behave in a particular state.

Object Class

Let’s consider a class of Animal, which can have an object like Dog, Cow, Lion, Elephant, etc. Each of these animals has different properties like name, breed, age, and color.

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    } 

    //Instance methods
    public String getName()
    {
        return name;
    } 

    public String getBreed()
    {
        return breed;
    } 

    public int getAge()
    {
        return age;
    } 

    public String getColor()
    {
        return color;
    }
    //methods override from Object class
	@Override
	public String toString() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}

Example of an object: Dog

Declaration of Object

We declare a variable or object like (type variable_name;). This indicates to the compiler that this variable refers to data whose type is type. In the case of the primitive type, declaration allocates space for the variable as per type but in case of a reference variable, the type must be a concrete class name. Generally, In java, we don’t create an object of Abstract class and interface.

Syntax

access_modifier class_name object_name;

Example

Animal dog_tommy;

As declared above for variable dog_tommy, show this variable is of type Animal but this will not create any object instance i.e point to undetermined value (null) as long as an object not created.

Creation & Initializing an object

When we create an instance of an object by using the new operator. It will allocate memory for a new object and return a reference to that memory. This new operator also called the class constructor to initialize the attributes of the class.

Syntax

//default constructor
access_modifier class_name object_name=new class_name();
//parameterize constructor
access_modifier class_name object_name=new class_name(arg1,arg2..);

Example

//Default Constructor
Animal dog_tommy=new Animal();

//Parameterize Constructor
Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");

Note :

  • All classes have at least one constructor. If you do not explicitly declare any constructor, then on time of compile Java compiler will automatically provide a no-argument constructor i.e also called the default constructor.
  • If you declare any parameterize constructor then that is must write a default constructor.
  • This default constructor calls the parent’s class no-argument constructor i.e super(); or if no parent class extended the called constructor of Object Class i.e directly or indirectly parent class of all the class.

Complete Example

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    } 

    //Instance methods
    public String getName()
    {
        return name;
    } 

    public String getBreed()
    {
        return breed;
    } 

    public int getAge()
    {
        return age;
    } 

    public String getColor()
    {
        return color;
    }
    //methods override from Object class
	@Override
	public String toString() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}

public TestClass
{
	public static void main(String[] args)
	{
	 //Instance Default Constructor
	 Animal dog_tommy=new Animal();

	 //Instance with Parameterize Constructor
     Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");
	}
}

Output


Animal [name=Default, breed=null, age=0, color=null]
Animal [name=Tommy, breed=Small Dog, age=5, color=Black]

Ways to create an object of a class

This is the most common way to create an instance of an object by using new operators. Java also provides other ways to create instances of an object but internally uses a new keyword only.

  1. Object by new Operator
  2. Object by Class.forName().newInstance()
  3. Object by clone() method
  4. Object by Deserialization
  5. Object for Anonymous Class

Follow this link to know about each object creation ways in detail: Java: Object Creation Ways

 

Java : Object Creation Way


In java objects can be created by five ways as follows:

  1. Object Creation by new
  2. Object Creation by reflection Class.newInstance() method.
  3. Object Creation by clone() method
  4. Object creation by the Annonymous Object.
  5. Object Creation by  Deserialization

Object Creation Way Example

Here is a complete example after considering all ways for object creations:

ackage objects;

import java.io.Serializable;

//Cloneable and Serializable is marker interface
public class Calculation implements Cloneable, Serializable{
	public int x=5;
	void fact(int n) {
		int fact = 1;
		for (int i = 1; i <= n; i++) {
			fact = fact * i;
		}
		System.out.println("factorial is " + fact);
	}
	public Object clone()throws CloneNotSupportedException{
		return super.clone();
		} 

}

package objects;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectCreationWay {

	public static void main(String[] args) {
		System.out.println("Object Creation by New");
		// Object Creation by using New
		Calculation cal = new Calculation();
		cal.fact(3);

		System.out.println("\nObject Creation by Reflection");
		// Object creation by newInstance method by reflection
		try {
			Class calculationClass = Class
					.forName("objects.Calculation");
			Calculation calc = (Calculation) calculationClass.newInstance();
			calc.fact(5);
		} catch (ClassNotFoundException |IllegalAccessException |InstantiationException ex) {
			ex.printStackTrace();
			//Multiple exception in single catch example in java  7
		} 

		System.out.println("\nObject Creation by Clone");
		/**
		 * Object creation by clone
		 */
		try {
			System.out.println(cal.x);
			Calculation cal2 = (Calculation) cal.clone();
			System.out.println(cal2.x);
			cal.x=10;
			//No change on clone object
			System.out.println(cal2.x);
		} catch (CloneNotSupportedException ex) {
			ex.printStackTrace();
		}

		System.out.println("\nObject Creation by Annonymous");
		/**
		 * Annonymous simply means nameless.An object that have no reference is
		 * known as annonymous object. If you have to use an object only once,
		 * annonymous object is a good approach.
		 */
		// calling method with annonymous object
		new Calculation().fact(5);

		System.out.println("\nObject Creation by  Deserialization");
		//By using deserialization of serialize object

		searializeObject(); //method to serialization of calculation object

		//By deserialization create object of Calculation Object

		Calculation c=deserializationOfObject();
		c.fact(5);

	}
	//serialize from java object to Object Stream
	public static void searializeObject()
	{
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(
					"calculator.ser");

			ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

			Calculation c= new Calculation();
			c.x=12;
			//serialization of object
			objectOutputStream.writeObject(c);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	//deserialization of objectStream to Java object
	public static Calculation deserializationOfObject()
	{

			Calculation c = null;

			try {
				FileInputStream fileInputStream = new FileInputStream("calculator.ser");

				ObjectInputStream objectInputStream = new ObjectInputStream(
						fileInputStream);

				c = (Calculation) objectInputStream.readObject();

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {

				e.printStackTrace();
			}

			return c;
	}

}

Output


Object Creation by New
factorial is 6

Object Creation by Reflection
factorial is 120

Object Creation by Clone
5
5
5

Object Creation by Annonymous
factorial is 120

Object Creation by  Deserialization
factorial is 120