Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

readme.md

Outline

Constructors

Default and Parameterized Constructors

Object Initialization

Java memory model

  • instances are created inside the heap

  • if you want to use super(), i.e. parent class constructor, then it must be the first statement inside the constructor.

Constructor chaining with this() and super()

calling same class's constructors with this()

public class Employee{
    public Employee(){
    }
    public Employee(String firstName){
        this(); // calling default constructor
    }
    public Employee(String firstName, String lastName){
        this(firstName); // calling constructor with single argument of String type
    }
}

calling parent class's constructors with super()

public class Parent{
    public Parent(){
        //...
    }
}
public class Child extends Parent{
    public Child(){
        super(); // invokes Parent's constructor
    }
}

private constructor

  • used in Singleton Pattern

A common singleton class definition looks like this:

import java.io.Serializable;

public class DemoSingleton implements Serializable{
    private static final long serialVersionUID = 1L;
    private DemoSingleton(){
        // private constructor
    }
    private static class DemoSingletonHolder{
        public static final DemoSingleton INSTANCE = new DemoSingleton();
    }
    public static DemoSingleton getInstance(){
        return DemoSingletonHolder.INSTANCE;
    }
    protected Object readResolve(){
        return getInstance();
    }
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.