Java Tutorial

Basic Concepts

Object Oriented Concepts

Coming Tutorials

>Home>Java Tutorial>Number of Ways to Create an Object in Java

Java Tutorial

Basic Concepts

Object Oriented Concepts

Coming Tutorials



What is an object in Java? Number of Ways to Create an Java Object

An object is a physical entity which can have a state (data) and behaviour (logic). The Java objects represent the real world physical or logical entities like mango, Honda Unicorn, iPhone 8, a particular bank account, etc.

Real-world objects share two characteristics: They all have state and behaviour. For example, Bicycles also have state (current gear, current pedal cadence, and current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail).



Java Object creation

Syntax:

ClassName referenceVariableName = new constructorname();

Example:


Student stud = new Student();

The object creation includes the following phases.

  • Declaration: Student is the class name which represents that reference variable stud will refer to the object of Student class or sub classes of Student class.

    Example: int a; In this variable declaration int represents that variable a will hold only integer type value.

    Similarly, Student stud; in this statement Student represents that stud is a reference variable and that can refer / point to an object of Student class or sub class of the Student class.

    The reference variables get stored in the stack memory.

    The default value of reference variable is null.

  • Instantiation: The new keyword is responsible to allocate memory space to the newly created object in the heap area. Creating an object of a class is also called instantiation of the class.

  • Initialization:The new operator is followed by a call to a constructor, which initializes the new object, assigns values to the instance variables.

    Note: Here, stud is not an object nor an instance, it is a reference variable or implicit pointer or restricted pointer.


Number of ways to create an object in Java

  1. Using new keyword: It is the simplest, common and regular way to create an object in Java. By using this object creation method we can call any default or parameterized constructor. This object creation way is required when you are passing values to the parameterized constructor at the time of an object creation.
  2. Example:

    
    Student stud1 = new Student(11, "Rajveer");
      

    In the above example stud1 is a reference variable that refer to the created object, new keyword is responsible to allocate memory to the object. In the statement a 2 parameterized constructor will get called.

  3. Using newInstance() method of Class class: The Class class has a newInstance() method to create an object of a class. This newInstance() method calls the default or no-argument constructor to create the Java object.

    We can create an Java object by newInstance() method like below example :

    
    Student stud = (Student)Class.forName("Student").newInstance();
      

    Or:

    
    Student stud = Student.class.newInstance();
      
  4. Using newInstance() method of Constructor class: The java.lang.reflect. The Constructor class has a newInstance() method to create an java object. In following way we can use newInstance() method of Constructor class to create an object.

    
    Constructor<Student> constructor = Student.class.getConstructor();
    Student stud = constructor.newInstance();
      

    The above two ways are reflective ways to create an java object using newInstance() method. The newInstance() method of the Class class internally uses the newInstance() method of the Constructor class. The newInstance() method of Constructor class is preferred and used by different frameworks like Spring, Hibernate, Struts, etc.

  5. Using clone() method: The Object class has a protected clone() method, if we call clone() on any object, the JVM internally creates a new java object and copies all content of the existing object into new one. This way of creating an object using the clone() method does not invoke any constructor.

    To use clone() method on an object we need to implement Cloneable interface and override the clone() method into that class. If we call clone() method on a object and that class is not implementing the Cloneable interface then we will get CloneNotSupportedException.

    
      Student stud = (Student) oldstud.clone();
      
  6. Using deserialization: Whenever we serialize and deserialize an object, the JVM creates a separate object. In deserialization, the JVM doesn’t use any constructor to create the object.

    To serialize and deserialize an object we need to implement the Serializable interface in our class.

    
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("sample.txt"));
    Student stud = (Student) in.readObject();
    

Uses of an Object

  1. An object is used to instantiate a class and that will represents a real world entity.

    Example: For class Bike we can create an object to represent a particular bike model say Honda Unicorn.

    
    Bike unicorn = new Bike();
    
  2. An object can be used to access class members.

    Example 1:

    
    unicorn.topSpeed =180; // assigning value to a variable
    
    unicorn.setTopSpeed(180); // assigning value through method
      
  3. If you have to use an object only once then you do not need to declare a reference variable.


    Example 2:

    
    Bike b1 =  new Bike();
    int totalBikes = b1.getNoOfBikes();
      

    is same as

    
      int totalBikes =  new Bike().getNoOfBikes();

    What is difference between object and instance?

    Answer: An object is an instance of a class, it means when we instantiate a class that creates an object. An instance of a class is a particular memory area which represents an object of the class. We can also call a particular single object is an instance.


    What is difference between object and Object and Objects in Java?

    Answer: An object with small/lower case ‘o’ is an instance of a class.

    The java.lang.Object with capital/uppercase ‘O’ is a root or parent class in Java that have 11 general purpose methods.

    The java.lang.Objects class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.

Share the article to help your friends