Monday, 17 August 2015

Creating an object instance with out using new keyword in Java

Java supports both primitive types and non-primitive types. Primitive types are nothing but int, char, float, boolean, double etc. Non-primitive types are any classes like String, File or any other user defined types. Although primitive types can be created with out using new keyword, most of non-primitive types need new keyword.

Assume that we have the following classes defined. Student with out constructor and Book with constructor.

class Student
{
    String name;
    int marks;
    char section;
}

class Book
{
    Book(String name, String title)
    {
        this.name = name;
        this.title = title;
    }
    String name;
    String title;
}


There are essentially three ways in which we can create an object with out using the new keyword.

Using reflection

import java.lang.reflect.*;

class CreateObjectUsingReflection
{
        public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException
        {
            // Creating an object with default constructor
            Class studentClass = Class.forName("Student");
            Student rick = (Student) studentClass.newInstance();
            rick.name = "Rick";
            System.out.println(rick.name);
            // Creating an object with two strings constructor
            Class bookClass = Class.forName("Book");
            Constructor twoStringsConstructor = bookClass.getDeclaredConstructor(String.class, String.class);
            Book learn_java = (Book) twoStringsConstructor.newInstance("Learn Java Perfectly", "Merit Campus");
            System.out.println(learn_java.title + " with " + learn_java.author);
        }
}


Try this program now

No comments:

Post a Comment