5 different ways to create objects in Java

Java Programming Java8Object Oriented Programming

Consider a class Tester which has implemented Cloneable interface. Now you can initialize an object using following five ways:

1. Using new keyword.

Tester tester1 = new Tester();

2. Using Class.forName() method

Tester tester2 = (Tester)Class.forName("Tester").newInstance();

3. Using clone method.

Tester tester3 = tester1.clone();

4. Using Constructor.forName() method

Tester tester4 = Tester.class.getConstructor().newInstance();

5. Using Deserialization

ObjectInputStream objectInputStream = new ObjectInputStream(inputStream );
Tester tester5 = (MyObject) objectInputStream.readObject();

 Using new keyword is the most preferred one.

Published on 23-Apr-2018 10:37:59