Methods of creating Objects in Java with examples

In our previous post I discussed about the classes and the objects and have also shown some examples of how to use a class and what is the purpose of a class and its objects. In this tutorial I am gonna dicuss about the ways of creating an object in Java.

So basically there are 4 ways of creating an object in Java and the rest I don’t know :P. These are-

  • Using new keyword.
  • Using getinstance() method.
  • Using clone of existing object.
  • Using Object deserialization.
java
java

Using new keyword.

This is the most conventional way of creating the objects and I think most of the objects get their life through this(‘new’) keyword only.

/**
 * Class which is being tested.
 */
class Codingeek {

	String message;
	
	/**
	 * Constructor that sets the message value.
	 */
	public Codingeek(String message) {
		this.message = message;
	}
	
	public void printMessage() {
		System.out.println(message);
	}
}

public class CreateObjectWithNew{
	
	/**
	 * Main method or program entry point.
	 */
	public static void main(String[] args) {
		Codingeek object1 = new Codingeek("Object 1");
		Codingeek object2 = new Codingeek("Object 2");

		object1.printMessage();
		object2.printMessage();
	}
}
Output:
Object 1
Object 2

Using New Instance method-

If your class has a default public constructor then you can use this method to instantiate your class.

public class CreateObjectWithNewInstance {
	/**
	 * Main method or program entry point.
	 */
	public static void main(String[] args) {

		try {
			Codingeeks object1 = (Codingeeks) Class.forName("Codingeeks").newInstance();
			object1.printCounter();
			
			Codingeeks object2 = (Codingeeks) Class.forName("Codingeeks").newInstance();
			object2.printCounter();
		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException e) {
			e.printStackTrace();
		}

	}
}

class Codingeeks {

	static int i = 10;

	/**
	 * Constructor that sets the message value.
	 */
	public Codingeeks() {
		i++;
	}

	public void printCounter() {
		System.out.println("Value of i = " + i);
	}

}
Output:-
Value of i = 11
Value of i = 12

Using CLONE of existing object.

We can use cloning to create a copy of the existing object in memory and use it as a seperate object. Various things that we should keep in mind while using this method is that.

  • Here we are creating the clone of an existing Object and not any new Object.
  • Clone method is declared protected in Object class. So it can be accessed only in subclass or in same package. And this is the reaason why we have to override this method in our class
  • Class need to implement Cloneable Interface otherwise it will throw CloneNotSupportedException.
public class CreateObjectWithClone {
	/**
	 * Main method or program entry point.
	 */
	public static void main(String[] args) {

		try {
			Codingeeks object1 = new Codingeeks();
			object1.printCounter();

			Codingeeks object2 = (Codingeeks) object1.clone();
			object2.printCounter();

		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}

	}
}

class Codingeeks implements Cloneable {

	static int i = 10;

	/**
	 * Constructor that sets the message value.
	 */
	public Codingeeks() {
		i++;
	}

	public void printCounter() {
		System.out.println("Value of i = " + i);
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		return super.clone();
	}
}
Output:-
Value of i = 11
Value of i = 11

** As we can see here that value of ‘i’ remains same even after we have created a copy of the object, it is because we did not create any new object and hence its constructor is not called where we have written the logic of incrementing the value of “i”.

Using Object Deserialization.

We can also use the method of Deserialisation to create an object. This process is nothing but to create an object from its serialised form i.e. in the process of serialisation we convert the object into stream of bytes so that it could be persisted on a remote location or in the database or and other means of storage. This persisted object can later be used at anytime to create and restore the object and we call this process as deserialisation.

Thats all from myside guys and if you know about any other method of object creation then please enlight us by sharing you knowledge with us.

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index