What are the different ways to create an object in Java

Java Programming Java8Object Oriented Programming

We can create object using multiple ways. Using new keyword is most prevalent one. Following are the various ways to create/initialize objects.

Using new keyword.

Tester tester1 = new Tester();

Using Class.forName() method

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

Using clone method.

Tester tester3 = tester1.clone();

Using Constructor.forName() method

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

Using Deserialization

ObjectInputStream objectInputStream = new ObjectInputStream(inputStream );
Tester tester5 = (MyObject) objectInputStream.readObject();
Published on 23-Apr-2018 00:07:56