GFG Day 9: Constructors and Encapsulation

sri parthusri parthu
8 min read

Java Constructors

  • In Java, a constructor is a special block of code that plays an important role in creating an object. The main purpose of initializing the object is to set up its internal state or to assign default values to its attributes.

Key Points

  • A constructor has the same name as the class.

  • Constructors don’t have any return type, not even void.

  • The constructor is automatically called when the object is created

Syntax

class ClassName {
    // Constructor
    ClassName() {
        // initialization code
    }
}

Example: Basic Constructor

public class Student {
    // Constructor
    public Student() {
        System.out.println("Constructor called! Object created.");
    }

    public static void main(String[] args) {
        Student s1 = new Student();  // Constructor is called here
    }
}

Output

Constructor called! Object created.

Note: It is not necessary to write a constructor for a class. It is because the Java compiler creates a default constructor (constructor with no arguments) if your class doesn't have any.

Constructor vs Method in Java

ConstructorMethod
→ Constructor name and class should have the same name.→ Whereas the method and class name should be different.
→ Constructor will not have return type void, return→ Whereas the method will have return type
→ The constructor will be called automatically once object is created→ Whereas the method have to called for execution.

Types of Constructor

  • In constructor we have 2 types: default constructor and parameterized constructor

    1. Default constructor: The default constructor will be automatically created by the Java compiler if no constructor is explicitly defined in the class. Then Java initializes variables to the default values (e.g., 0 for integer, false for Boolean, null for object references).

Example: Default Constructor

class Car {
    int speed;

    public static void main(String[] args) {
        Car c = new Car();  // Java provides default constructor
        System.out.println(c.speed);  // Default value = 0
    }
}

Explanation

  • The car class does not have any constructor defined explicitly.

  • Java automatically provides a default constructor that initializes speed to their default values (0 in this case).

    1. parameterized constructor: The parameterized constructor allows initialization of variables with specific values provided during object creation. It is useful when you need more control over how objects are initialized.

Example: Parameterized Constructor

class Employee {
    String name;
    int id;

    // Parameterized constructor
    public Employee(String empName, int empId) {
        name = empName;
        id = empId;
    }

    public void display() {
        System.out.println("Name: " + name + ", ID: " + id);
    }

    public static void main(String[] args) {
        Employee e1 = new Employee("John", 101);
        e1.display();  // Output: Name: John, ID: 101
    }
}

Explanation:

  • The Employee class has a parameterized constructor Employee(String empName, int empId).

  • When the object e1 is created with new Employee("John", 101), the constructor is called, and empName and empId are initialized to John and 101, respectively.

Constructor Overloading

  • Java supports multiple constructors with the same name but different parameter lists. This is known as constructor overloading.

You can create multiple constructors with different parameter lists.

class Rectangle {
    int length, width;

    // No-arg constructor
    public Rectangle() {
        length = 10;
        width = 5;
    }

    // Parameterized constructor
    public Rectangle(int l, int w) {
        length = l;
        width = w;
    }

    public void area() {
        System.out.println("Area = " + (length * width));
    }

    public static void main(String[] args) {
        Rectangle r1 = new Rectangle();      // Calls no-arg
        Rectangle r2 = new Rectangle(20, 15); // Calls parameterized

        r1.area();  // Area = 50
        r2.area();  // Area = 300
    }
}

Output

Area = 50
Area = 300

Java's this Keyword

What is a this keyword?

  • In Java, this is a reference variable that refers to the current object. the object on which the method or constructor is being called.

  • It is commonly used in constructors and methods to differentiate between instance variables and parameters.

Why Do We Use this in Java?

  • Below are the main uses of this:

    1. To refer to current class instance variables.

    2. To invoke the current class constructor.

    3. To pass the current object as an argument.

    4. To return the current object from a method.

    5. To invoke the current class method.

Use Case 1: Refer Current Class Instance Variable

When local variables (like constructor parameters) have the same name as instance variables:

class Student {
    int id;
    String name;

    public Student(int id, String name) {
        this.id = id;         // 'this.id' refers to instance variable
        this.name = name;     // 'name' is the constructor parameter
    }

    public void display() {
        System.out.println(id + " " + name);
    }

    public static void main(String[] args) {
        Student stud = new Student(1, "Funky");
        stud.display();
    }
}

Output

1 Funky

Use Case 2: Invoke Current Class Constructor

class Student {
    int id;
    String name;

    // Default constructor
    public Student() {
        this(101, "Fon Jon"); // Calls the parameterized constructor
    }

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

    // Method to display student details
    public void display() {
        System.out.println(id + " " + name);
    }

    // Main method to run the program
    public static void main(String[] args) {
        Student s1 = new Student(); // Calls default constructor
        s1.display();               // Output: 101 Parthu

        Student s2 = new Student(102, "Don Jon"); // Calls parameterized constructor
        s2.display();               // Output: 102 Sriparthu
    }
}

Output

101 Fon Jon
102 Don Jon

Use Case 3: Pass Current Object as Argument

class A {
    public void display(A obj) {
        System.out.println("Method called with object: " + obj);
    }

    public void callMethod() {
        display(this); // Passing current object
    }

    public static void main(String[] args) {
        A obj1 = new A();
        obj1.callMethod();
    }
}

Output

Method called with object: A@473b46c3

Use Case 4: Return Current Class Instance

class Student {
    // Method that returns the current object
    Student getStudent() {
        return this;
    }

    void display() {
        System.out.println("getStudent() returned: " + this);
    }

    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = s1.getStudent(); // Returns the same object s1

        s1.display();

        // Optional: Check if s1 and s2 are the same
        if (s1 == s2) {
            System.out.println("s1 and s2 refer to the same object.");
        } else {
            System.out.println("s1 and s2 refer to different objects.");
        }
    }
}

Output

getStudent() returned: Student@345965f2
s1 and s2 refer to the same object.

Use Case 5: Invoke Current Class Method

class Demo {
    void show() {
        System.out.println("Show method called");
    }

    void display() {
        this.show(); // Explicit use of this to call method
    }

    public static void main(String[] args) {
        Demo obj = new Demo();
        obj.display(); // Calls show() via this inside display()
    }
}

Output

Show method called

Advantages of this Keyword

  1. Avoids Naming Conflicts: Resolves ambiguity when instance variables and method parameters have the same name.

  2. Simplifies Method Chaining: Allows multiple methods to be called on the same object in a single statement.

  3. Supports Constructor Overloading: Enables constructors to call each other, reducing redundant code.

  4. Provides Object Context: Helps identify the object currently executing the method.

Disadvantages of Using "this" Reference

  1. Overuse of this can make the code harder to read and understand.

  2. Using this unnecessarily can add unnecessary overhead to the program.

  3. Using this in a static context results in a compile-time error.

  4. Overall, this keyword is a useful tool for working with objects in Java, but it should be used judiciously and only when necessary.


Encapsulation in Java

What is Encapsulation?

  • Encapsulation is one of the four core OOP principles (along with abstraction, inheritance, and polymorphism).
    It is the process of wrapping the data (variables) and the code (methods) acting on the data into a single unit, typically a class.

  • It is mainly used to protect data from unauthorized access and to achieve data hiding.

Key Concepts of Encapsulation

  • Make all the data private.

  • Provide public getter and setter methods to access or update the data.

  • Helps in controlling how the variables are accessed or modified.

Real-World Analogy

  • Think of a capsule pill—it hides all the ingredients inside. You just consume it without seeing or changing what’s inside.

  • In programming, encapsulation hides data inside a class and allows access only through controlled methods.

Encapsulation Example in Java

// File: Student.java
class Student {
    // Step 1: Private data members
    private int rollNumber;
    private String name;

    // Step 2: Public getter and setter methods
    public int getRollNumber() {
        return rollNumber;
    }

    public void setRollNumber(int rollNumber) {
        this.rollNumber = rollNumber;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
// File: Main.java
public class Main {
    public static void main(String[] args) {
        Student s = new Student();

        // Setting values using setter methods
        s.setRollNumber(101);
        s.setName("JON BON");

        // Getting values using getter methods
        System.out.println("Roll No: " + s.getRollNumber());
        System.out.println("Name: " + s.getName());
    }
}

Output

Roll No: 101
Name: JON BON

Advantages of Encapsulation

  1. Data Hiding: Internal object details are hidden from the outside world.

  2. Security: Prevents unauthorized access.

  3. Control: You can control what is stored in the variables.

  4. Maintenance: Code is easier to manage and understand.

  5. Improved Flexibility: Change the internal implementation without affecting external code.


Happy Learning

Thanks For Reading! :)

SriParthu 💝💥

0
Subscribe to my newsletter

Read articles from sri parthu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

sri parthu
sri parthu

Hello! I'm Sri Parthu! 🌟 I'm aiming to be a DevOps & Cloud enthusiast 🚀 Currently, I'm studying for a BA at Dr. Ambedkar Open University 📚 I really love changing how IT works to make it better 💡 Let's connect and learn together! 🌈👋