DEV Community

velvizhi Muthu
velvizhi Muthu

Posted on

Module-3 Constructor

01. What is a Constructor?

1. Whenever we create an object, the constructor will call automatically.

2. The constructor's name must be the same as the class name.

3. A constructor must not have a return type.

4. The default constructor is invisible.

    5. A constructor is used to initialise the state of an object.

    6. The constructor is invoked implicitly.

    7. The Java compiler provides a default constructor if we do not have any constructors in a class.

    8."this" is a Java keyword.
Enter fullscreen mode Exit fullscreen mode

02. How many types of constructors?

  1. Default constructor (No argument )
  2. Parameterised constructor (With argument)

03. What is the Default constructor (No argument )?
When a constructor does not have any parameters, it is known as a default constructor.

Syntax:

(){}

Rule: If there is no constructor in a class, the compiler automatically creates a default constructor.

04. What is the purpose of a default constructor?
The default constructor is used to provide the default values to the object, like 0, null, etc., depending on the type.

05. What is the Parameterised Constructor or with argument constructor?
A constructor that has a specific number of parameters is called a parameterised constructor.

06. Why use the parameterised constructor?
The parameterised constructor is used to provide different values to distinct objects. However, you can also provide the same values.

07. What is the method?

  1. A method is used to expose the behaviour of an object.
  2. A method must have a return type
  3. The method is invoked explicitly.
  4. The method is not provided by the compiler in any case.
  5. The method name may or may not be the same as the class name.

Real-time Program:

class Employee {
// Fields (properties)
String name;
int id;
double salary;

// Constructor to initialise the object
public Employee(String empName, int empId, double empSalary) {
    name = empName;
    id = empId;
    salary = empSalary;
    System.out.println("Employee object created successfully!");
}

// Method to display employee details
public void displayDetails() {
    System.out.println("Employee ID: " + id);
    System.out.println("Employee Name: " + name);
    System.out.println("Salary: ₹" + salary);
}

public static void main(String[] args) {
    // Creating Employee objects using the constructor
    Employee emp1 = new Employee("Nanthakumar", 101, 55000.50);
    emp1.displayDetails();

    System.out.println();

    Employee emp2 = new Employee("Priya", 102, 62000);
    emp2.displayDetails();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)