Java OOPs Concepts Made Simple: A Complete Beginner-Friendly Guide (Part-4)

Java Constructors, this & super Keywords, Singleton Class

Master Constructors, this, super, Default Constructors, Constructor Chaining, Singleton Pattern and more.


Introduction

In the previous OOPS blog, we explored concepts like inheritance, polymorphism, composition, aggregation, interfaces and abstract classes. Now it's time to understand another important part of Java OOPS—how objects are initialized and how child classes communicate with parent classes.

In this guide you'll learn:

  • Constructors in Java
  • Default Constructors
  • Constructor Chaining
  • this keyword
  • super keyword
  • this vs super
  • Singleton Class

Constructors in Java

A constructor is a special method that is called automatically whenever an object is created. Its main purpose is to initialize object data.

Definition
A constructor is a special method called automatically during object creation to initialize objects.

Why Do We Need Constructors?

Let's understand this with examples.

Example 1: Default Values

class Student{
    String name;
    int rollNo;
}

public class Main{
    public static void main(String[] args){
        Student s1 = new Student();
        Student s2 = new Student();
    }
}
Output:
name = null
rollNo = 0

Java gives default values, but that's usually not what we want.

Example 2: Hardcoded Values

class Student{
    String name="Ravi";
    int rollNo=101;
}
Now every object gets exactly the same values.
Ravi
101
This isn't useful when every student is different.

Example 3: Manual Assignment

class Student{
    String name;
    int rollNo;
}

public class Main{
    public static void main(String[] args){
        Student s1=new Student();
        s1.name="Ravi";
        s1.rollNo=101;

        Student s2=new Student();
        s2.name="Sriram";
        s2.rollNo=102;
    }
}
This works. But imagine writing assignments for 20 variables every time. The code becomes lengthy and difficult to maintain.

Example 4: Using Constructor (Best Approach)

class Student{
    String name;
    int rollNo;

    Student(String name,int rollNo){
        this.name=name;
        this.rollNo=rollNo;
    }
}

public class Main{
    public static void main(String[] args){

        Student s1=new Student("Ravi",101);
        Student s2=new Student("Sriram",102);
    }
}
Now each object gets customized values in a single line. This is exactly why constructors exist.

Constructor Rules

Rule Explanation
Return Type Constructors do not have a return type.
Access Modifiers Can be public, private, protected or default.
Name Must match the class name.
Automatic Execution Runs automatically during object creation.

Constructor with Return Type?

If a method has a return type even void — it is no longer a constructor.
class Student{
    Student(String name,int rollNo){
    }

    void Student(){
        System.out.println("This is a method.");
    }
}
Output
This is a method.
Although this is valid Java, it is not considered good programming practice.

Default Constructor

If you don't write any constructor, Java automatically provides one. Internally it looks like this.
Student(){
    super();
}
Important points:
	No arguments
	Compiler generated
	Calls `super()`
	Access modifier matches the class

Example 1

Programmer's Code
class Student{
}
Compiler Generates
class Student{
    Student(){
        super();
    }
}

Example 2

Programmer's Code
public class Student{
}
Compiler Generates
public class Student{
    public Student(){
        super();
    }
}

Example 3

Programmer's Code
class Student{
    void print(){
    }
}
Compiler Generates
class Student{
    Student(){
        super();
    }

    void print(){
    }
}

Example 4

If a constructor already calls `this()`, the compiler does not insert another `super()`.
class Student{
    Student(){
        this(10);
    }

    Student(int x){
    }
}
Internally:
class Student{
    Student(){
        this(10);
    }

    Student(int x){
        super();
    }
}

Constructor vs Instance Block

Both execute during object creation, but they serve different purposes.
Constructor Instance Block
Used for object initialization. Used for tasks other than initialization.
Runs when constructor executes. Runs before constructor.

A common use case is counting objects.
class Student{
    static int count=0;

    Student(){
        count++;
    }

    Student(int x){
        count++;
    }
}

public class Main{
    public static void main(String[] args){
        Student s1=new Student();
        System.out.println(Student.count);

        Student s2=new Student(10);
        System.out.println(Student.count);
    }
}
Output
1
2

Constructor Overloading

Constructors can be overloaded.
class Student{
    Student(){
        System.out.println("No-arg Constructor");
    }

    Student(int x){
        System.out.println("Int Constructor");
    }
}
Remember:
	Constructors can be overloaded.
	Constructors cannot be overridden.
	Constructors are not inherited.

Constructor Isn't Inherited

class Person{
    Person(){
    }
}

class Student extends Person{
    Student(){
        super();
    }
}
Every class has its own constructor. Even abstract classes can have constructors. The only exception is interfaces, because interfaces don't have constructors.

this Keyword in Java

In Java, the this keyword is a reference variable that refers to the current class instance (current object).

Whenever you create an object, this points to that object's memory location. It is mainly used when working with constructors, instance variables, and methods inside the same class.

Definition
The this keyword refers to the current object of the class.

Use Cases of this Keyword

  • To refer to current class instance variables (this.variableName)
  • To invoke current class methods (this.methodName())
  • To invoke another constructor of the same class using this()

Let's understand all three use cases with a single example.

Complete Example

class Student {
    String name;
    int age;

    // Default constructor
    Student() {
        // Constructor chaining
        this("Unknown", 0);
        System.out.println("Default constructor executed.");
    }

    // Parameterized constructor
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    void showDetails() {
        System.out.println("Student Name: " + this.name);
        System.out.println("Student Age: " + this.age);
    }

    void display() {
        this.showDetails();
    }
}

public class Main {
    public static void main(String[] args) {

        Student s1 = new Student();
        System.out.println("------------------------------");
        s1.display();

        System.out.println("------------------------------");
        Student s2 = new Student("Alex", 21);
        s2.display();
    }
}

Output

Default constructor executed.
------------------------------
Student Name: Unknown
Student Age: 0
------------------------------
Student Name: Alex
Student Age: 21

Understanding the Three Uses

1. Referring to Current Class Variables

Sometimes constructor parameters have the same names as instance variables.

Without this, Java gets confused because both names are identical.

Student(String name, int age) {
    this.name = name;
    this.age = age;
}

Here:

  • this.name refers to the instance variable.
  • name refers to the constructor parameter.

This removes the ambiguity.

2. Calling a Method of the Same Class

A method inside a class can call another method using this.

void display() {
    this.showDetails();
}

This explicitly tells Java to execute the showDetails() method of the current object.

Although writing only showDetails() also works, using this makes it clear that the method belongs to the current object.

3. Constructor Chaining using this()

One constructor can call another constructor of the same class.

Student() {
    this("Unknown", 0);
}

Instead of writing duplicate initialization code, the default constructor simply forwards the work to the parameterized constructor.

This technique is called constructor chaining.

Important Rule

Important: The this() call must always be the first statement inside a constructor.

Correct:

Student() {
    this("Unknown", 0);
}

Incorrect:

Student() {
    System.out.println("Hello");
    this("Unknown", 0);   // Compilation Error
}

Java throws a compilation error because this() is not the first statement.


Quick Recap

Use Example
Current object variable this.name
Current class method this.showDetails()
Current class constructor this()

super Keyword in Java

In Java, the super keyword is a reference variable used to refer to the immediate parent class object.

Whenever a child class inherits from a parent class, the super keyword allows the child class to access the parent class's members such as variables, methods, and constructors.

Definition
The super keyword refers to the immediate parent class object.

Why Do We Need super?

A child class can inherit everything from its parent class, but sometimes the child class defines its own variables or methods with the same names as the parent class.

In such situations, the child class needs a way to access the original members of the parent class. That's exactly what super is used for.

Use Cases of super Keyword

  • To access parent class instance variables using super.variableName
  • To invoke parent class methods using super.methodName()
  • To invoke the parent class constructor using super()

Let's understand all three use cases with one complete example.

Complete Example

// Parent class
class Animal {
    String name = "Parent Animal";

    Animal() {
        System.out.println("Parent Class: Animal constructor executed.");
    }

    void makeSound() {
        System.out.println("Parent Class: Animal makes a generic sound.");
    }
}

// Child class
class Dog extends Animal {
    String name = "Child Dog";

    Dog() {
        super();
        System.out.println("Child Class: Dog constructor executed.");
    }

    void displayInfo() {
        System.out.println("Child Variable: " + name);
        System.out.println("Parent Variable: " + super.name);
        super.makeSound();
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        System.out.println("----------------------------------");
        myDog.displayInfo();
    }
}

Output

Parent Class: Animal constructor executed.
Child Class: Dog constructor executed.
----------------------------------
Child Variable: Child Dog
Parent Variable: Parent Animal
Parent Class: Animal makes a generic sound.

Understanding the Three Uses

1. Accessing Parent Class Variables

When both parent and child classes contain variables with the same name, the child variable hides the parent variable.

String name = "Child Dog";
System.out.println(name);
System.out.println(super.name);

Output:

  • name → Child Dog
  • super.name → Parent Animal

This is useful whenever you want to access the hidden variable from the parent class.

2. Calling Parent Class Methods

A child class can also execute the original version of a method defined in the parent class.

super.makeSound();

This becomes especially useful when the child class overrides a method but still wants to use the parent's implementation.

For example:

class Animal {
    void makeSound() {
        System.out.println("Generic Sound");
    }
}

class Dog extends Animal {
    void makeSound() {
        super.makeSound();
        System.out.println("Bark");
    }
}

Output:

Generic Sound
Bark

Here, the child class first executes the parent's method and then adds its own behavior.

3. Calling Parent Class Constructor

Whenever a child object is created, Java automatically executes the parent class constructor first.

This happens through super().

Dog() {
    super();
    System.out.println("Dog constructor executed.");
}

The execution order becomes:

  1. Parent constructor executes.
  2. Child constructor executes.

Even if you don't explicitly write super(), Java inserts it automatically when possible.


Important Rules of super

  • super() must always be the first statement inside a constructor.
  • Only one constructor call (this() or super()) is allowed as the first statement.
  • super can access only the immediate parent class.
  • It cannot be used inside a static method.

Correct Example

Dog() {
    super();
    System.out.println("Dog Created");
}

Incorrect Example

Dog() {
    System.out.println("Hello");
    super();     // Compilation Error
}

The compiler throws an error because super() is not the first statement.


Quick Recap

Use Example
Parent variable super.name
Parent method super.makeSound()
Parent constructor super()

this vs super in Java

Both this and super are reference variables in Java, but they point to different objects.

The this keyword refers to the current class object, whereas the super keyword refers to the immediate parent class object.

Although both are commonly used inside constructors and methods, their purposes are completely different.

Quick Idea
Use this when you want to work with the current class, and use super when you need something from the parent class.

Difference Between this and super

Feature this super
Refers To Current class object Immediate parent class object
Access Variables this.variable super.variable
Call Methods this.method() super.method()
Constructor Call this() super()
Purpose Work with current class members Work with parent class members
Constructor Rule Must be first statement Must be first statement

Side-by-Side Example

The following example shows how both keywords behave inside a child class.

class Person {
    String name = "Parent";

    void showName() {
        System.out.println("Parent Method");
    }
}

class Student extends Person {
    String name = "Child";

    Student() {
        super();
    }

    void display() {
        System.out.println(this.name);
        System.out.println(super.name);
        this.showStudent();
        super.showName();
    }

    void showStudent() {
        System.out.println("Child Method");
    }
}

Here:

  • this.name accesses the child class variable.
  • super.name accesses the parent class variable.
  • this.showStudent() calls the child class method.
  • super.showName() calls the parent class method.

Constructor Chaining

One of the most common interview questions is the difference between this() and super().

this() super()
Calls another constructor in the same class. Calls the constructor of the parent class.
Used for constructor chaining within one class. Used to initialize the parent portion of an object.
Cannot be used together with super() in the same constructor. Cannot be used together with this() in the same constructor.

Example of this()

Student() {
    this("Unknown", 0);
}

This calls another constructor inside the same class.

Example of super()

Student() {
    super();
}

This calls the constructor of the parent class.


Important Rules to Remember

  • Both this() and super() must be the first statement inside a constructor.
  • You cannot use both this() and super() in the same constructor.
  • this works with the current class, while super works with the immediate parent class.
  • Both keywords can only be used in instance context and cannot be used inside static methods.

Easy Memory Trick

  • this → Think of Myself (Current Class).
  • super → Think of My Parent (Parent Class).

Whenever you're confused during coding, ask yourself one simple question:

"Am I working with my own class or my parent class?"

If it's your own class, use this. If it's the parent class, use super.


Singleton Class in Java

A Singleton Class is a class that allows only one object to be created throughout the entire application. Whenever another part of the program requests an object, it receives the same existing object instead of creating a new one.

This design pattern is useful when a single shared object is enough for the whole application, such as a database connection or system runtime.

Definition
A Singleton Class is a class for which only one object can be created.

Characteristics of a Singleton Class

  • Only one object is created.
  • The constructor is declared private.
  • A private static instance stores the single object.
  • A public static method returns that object whenever needed.

These four points form the foundation of the Singleton design pattern.


Built-in Examples of Singleton-like Classes

Java itself contains classes that behave like a single shared instance.

1. java.lang.System

The System class provides a single shared access point for system properties, standard input, standard output, and standard error.

System.out.println("Hello World");

Notice that we never create an object using new System(). We directly use its static members.

2. java.lang.Runtime

The Runtime class represents the application's runtime environment. Java provides only one runtime instance through the getRuntime() method.

Runtime runtime = Runtime.getRuntime();

Every call to getRuntime() returns the same runtime object.


Creating a Custom Singleton Class

Let's build our own Singleton class step by step.

class DatabaseConnection {
    // Step 1: Private static instance
    private static DatabaseConnection instance;

    // Step 2: Private constructor
    private DatabaseConnection() {
        System.out.println("Database Connection Created.");
    }

    // Step 3: Public method to access the single object
    public static synchronized DatabaseConnection getInstance() {

        if(instance == null){
            instance = new DatabaseConnection();
        }

        return instance;
    }

    public void connect(){
        System.out.println("Connected to database successfully.");
    }
}

public class Main {
    public static void main(String[] args){
        DatabaseConnection db1 = DatabaseConnection.getInstance();
        db1.connect();

        DatabaseConnection db2 = DatabaseConnection.getInstance();

        System.out.println(db1 == db2);
    }
}

Output

Database Connection Created.
Connected to database successfully.
true

The first call creates the object. Every later call returns the same object, so db1 == db2 becomes true.


Understanding Each Step

Step 1: Private Static Instance

private static DatabaseConnection instance;

This variable stores the only object of the class.

Step 2: Private Constructor

private DatabaseConnection(){ }

Since the constructor is private, no other class can create an object using the new keyword.

Step 3: Public Static Method

public static synchronized DatabaseConnection getInstance()

This method checks whether the object already exists.

  • If no object exists, it creates one.
  • If the object already exists, it simply returns it.

The synchronized keyword helps prevent multiple objects from being created in multithreaded programs.


Why Can't a Singleton Class Be Inherited?

One interesting interview question is:

The Singleton class isn't declared final. Then why can't we create a child class?

The answer is simple: the constructor is private.

Every child class constructor automatically calls the parent constructor using super(). But if the parent constructor is private, the child class cannot access it.

Example

class Person{
    private Person(){
    }
}

class Student extends Person{
    Student(){
        super();
    }
}

This code produces a compilation error because the child class is not allowed to call the private constructor of Person.

Remember: A Singleton class doesn't need to be declared final. A private constructor itself prevents object creation outside the class and also prevents successful inheritance.

Quick Revision

Concept Key Point
Constructor Automatically initializes objects.
Default Constructor Compiler provides it when no constructor exists.
this Refers to the current class object.
super Refers to the immediate parent class object.
this() Calls another constructor in the same class.
super() Calls the parent class constructor.
Singleton Class Allows only one object.
Private Constructor Prevents external object creation.

Conclusion

Constructors, this, super, and the Singleton pattern are among the most frequently asked Java interview topics because they explain how objects are created, initialized, and managed.

Once you understand these concepts, you'll find inheritance, constructor chaining, and object-oriented programming much easier to apply in real-world Java projects.


Continue Your Java Learning Journey

Enjoyed this guide? Explore more beginner-friendly Java tutorials, interview questions, and roadmap-based learning articles on RoadmapForJava.

Visit RoadmapForJava →

Keep learning, keep building, and become Java interview ready—one concept at a time.

Comments

Popular posts from this blog

Java Roadmap

Java OOPs Concepts Made Simple: A Complete Beginner-Friendly Guide (Part-2)

Identifiers