Creating Objects : New « Class Definition « Java Tutorial

  1. Using the new keyword.
  2. new is always followed by the constructor of the class.

For example, to create an Employee object, you write:

Employee employee = new Employee();

Here, 'employee' is an object reference of type Employee.

  1. Once you have an object, you can call its methods and access its fields, by using the object reference.
  2. You use a period (.) to call a method or a field.

For example:


The following code, for instance, creates an Employee object and assigns values to its age and salary fields:

public class MainClass {

  public static void main(String[] args) {
    Employee employee = new Employee();
    employee.age = 24;
    employee.salary = 50000;


class Employee {
    public int age;
    public double salary;
    public Employee() {
    public Employee(int ageValue, double salaryValue) {
        age = ageValue;
        salary = salaryValue;

When an object is created, the JVM also performs initialization that assign default values to fields.

5.20.1.Creating Objects
5.20.2.Memory Leak Demo