Loading
Java Static Keyword

Scenario 1: Using Static Variables, Methods, and Blocks in an Employee Management System

Scenario


You are tasked with designing an Employee management system. The company name is the same for all employees, but each employee has unique details like ID and name. Additionally, you want to display a welcome message as soon as the application starts, before any objects are created.


Question:

How would you use static variables, static methods, and static blocks in your Employee class to meet these requirements? Please explain your approach and provide a code example.


Answer:

To ensure the company name is shared among all Employee objects, I would declare it as a static variable. This way, there is only one copy of the company name, regardless of how many Employee instances are created. For displaying a welcome message before any object is created, I would use a static block, which executes when the class is loaded. If I need a utility function, such as displaying the company name, I would implement it as a static method so it can be called without creating an Employee object.


Example:

public class Employee {
    int id;
    String name;
    static String company = "Tech Innovators";

    // Static block for welcome message
    static {
        System.out.println("Welcome to the Employee Management System!");
    }

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // Static method to display company name
    public static void displayCompany() {
        System.out.println("Company: " + company);
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", company=" + company + "]";
    }

    public static void main(String[] args) {
        Employee.displayCompany(); // Calling static method without object

        Employee e1 = new Employee(1, "Alice");
        Employee e2 = new Employee(2, "Bob");

        System.out.println(e1);
        System.out.println(e2);
    }
}