Sunday 27 May 2018

newInstance(): Create an instance of the class

java.lang.Class provides ‘newInstance’ method to create an object to a class. The class must have default constructor to get an instance.

Employee.java
package com.sample.model;

public class Employee {

 private int id;
 private String name;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + "]";
 }

}

Test.java

package com.sample.test;

import com.sample.model.Employee;

public class Test {

 public static void main(String args[]) throws InstantiationException, IllegalAccessException {
  Class<Employee> clazz = Employee.class;

  Employee emp = clazz.newInstance();

  System.out.println(emp);
 }
}


When you ran ‘Test.java’, you can able to below messages in console.

Employee [id=0, name=null]

As you see, I do not provide any constructor to the class Employee. If a class do not have any constructor, then java provides default constructor.

‘newInstance’ method calls the default constructor and create the object. Let’s confirm this behavior with small experiment.

Employee.java

package com.sample.model;

public class Employee {

 private int id;
 private String name;
 
 public Employee() {
  System.out.println("Default constructor of employee is called");
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + "]";
 }

}

I added a default constructor and prints a message. When I ran Test.java, you can able to see below messages in the console.

Default constructor of employee is called
Employee [id=0, name=null]


Previous                                                 Next                                                 Home

No comments:

Post a Comment