DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-61 Java – Constructor Overloading and Key Concepts

Constructor Overloading

Constructor overloading means having multiple constructors in the same class with different parameter lists. This allows us to create objects in different ways based on the values we pass.

Example:

class Student {
    String name;
    int age;

    Student() {
        System.out.println("Default constructor called");
    }

    Student(String n, int a) {
        name = n;
        age = a;
    }
}
Enter fullscreen mode Exit fullscreen mode

Zero-Argument Constructor vs Default Constructor

  • Zero-Argument Constructor:

    A constructor with no parameters created by us in the class.

  • Default Constructor:

    Provided by Java automatically when we do not write any constructor in the class.
    It is also a zero-argument constructor but created by Java.

.

Naming of Constructor Variables

When we define parameters inside a constructor, their names should be meaningful to clearly indicate what data they hold. Usually, they are named the same as class variables for clarity, but to avoid confusion, we use the this keyword.

Example:

class Employee {
    int salary;

    Employee(int salary) {
        this.salary = salary; // 'this.salary' refers to class variable, 'salary' refers to parameter
    }
}
Enter fullscreen mode Exit fullscreen mode

this Keyword

The this keyword refers to the current object. It is mainly used to differentiate between class variables and constructor parameters when both have the same name.

Packages in Java

Packages group related classes and avoid name conflicts, making code organized and maintainable.

  • To compile a program with a package:
  javac -d . FileName.java
Enter fullscreen mode Exit fullscreen mode
  • To run:
  java packageName.className
Enter fullscreen mode Exit fullscreen mode
  • Example:

    • Compile: javac -d . InterestCalculation.java
    • Run: java com.indianBank.InterestCalculation

Top comments (0)