top of page
shubhangisingh453

Important Java Classes everyone should know



📗 Anonymous classes


Java anonymous classes are a way to create a one-time-use class that extends a class or implements an interface without having to define a named class. Anonymous classes are commonly used for event listeners and other interfaces with a single method. Here are the topics related to Java anonymous classes in detail with examples:


♦ Anonymous class syntax


An anonymous class can be created by using the new keyword followed by the class or interface to be extended or implemented, followed by an open and close curly brace. The body of the class is defined inside the curly braces.

Example:


interface HelloWorld {
    void greet();
}

public class AnonymousClassExample {
    public static void main(String[] args) {
        HelloWorld helloWorld = new HelloWorld() {
            @Override
            public void greet() {
                System.out.println("Hello, world!");
            }
        };
        helloWorld.greet();
    }
}

In this example, we define an anonymous class that implements the HelloWorld interface. We create an instance of the anonymous class and call its greet method, which outputs "Hello, world!" to the console.


♦ Anonymous class limitations


Anonymous classes have some limitations compared to named classes. For example, they cannot have a constructor, and they cannot declare any member variables. They can only declare final local variables.

Example:


public class AnonymousClassExample {
    public static void main(String[] args) {
        String message = "Hello, world!";
        new Object() {
            public void printMessage() {
                System.out.println(message);
            }
        }.printMessage();
    }
}

In this example, we define an anonymous class that extends the Object class and declares a printMessage method that outputs the value of the message variable. The message variable is a final local variable that is defined in the main method.


♦ Anonymous class event listeners


One of the most common uses of anonymous classes is for event listeners. An event listener is an object that listens for a specific event and responds to it. In Java, event listeners are typically implemented as interfaces with a single method.

Example:


import java.awt.*;
import java.awt.event.*;

public class AnonymousClassExample {
    public static void main(String[] args) {
        Frame frame = new Frame("Anonymous Class Example");
        Button button = new Button("Click me!");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Button clicked!");
            }
        });
        frame.add(button);
        frame.pack();
        frame.setVisible(true);
    }
}

In this example, we define an anonymous class that implements the ActionListener interface. We create a Button object and add the anonymous class as an event listener to the button. When the button is clicked, the anonymous class's actionPerformed method is called, which outputs "Button clicked!" to the console.


♦ Anonymous class inheritance


Anonymous classes can also extend a class instead of implementing an interface.

Example:


class Animal {
    public void speak() {
        System.out.println("Animal speaking...");
    }
}

public class AnonymousClassExample {
    public static void main(String[] args) {
        Animal animal = new Animal() {
            @Override
        public void speak() {
                System.out.println("Dog barking...");
            }
        };
        animal.speak();
    }
}

In this example, we define an anonymous class that extends the Animal class and overrides the speak method. We create an instance of the anonymous class and call its speak method, which outputs "Dog barking..." to the console.


📙 Singleton classes


Java Singleton Class is a design pattern that allows us to ensure that only one instance of a class is created and that it is globally accessible. It is often used in situations where we need to restrict the instantiation of a class to a single instance to control access to shared resources. Here are the topics related to Java Singleton Class in detail with examples:


♦ Basic Singleton Class implementation


To create a Singleton Class in Java, we need to follow the following steps:

  • Declare a private static variable of the class instance.

  • Define a private constructor to restrict the instantiation of the class from outside.

  • Provide a public static method that returns the instance of the class.

Example:


public class Singleton {
    private static Singleton instance;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

In this example, we define a Singleton Class called Singleton. We declare a private static variable instance to hold the instance of the class. We define a private constructor to prevent the creation of new instances of the class from outside the class. Finally, we define a public static method getInstance() that returns the instance of the class. If the instance variable is null, the method creates a new instance of the class and returns it.


♦ Thread-Safe Singleton Class implementation


The basic Singleton Class implementation is not thread-safe, meaning it can cause problems in a multi-threaded environment where multiple threads can access the class simultaneously. To make the Singleton Class thread-safe, we can use the synchronized keyword.

Example:


public class ThreadSafeSingleton {
    private static ThreadSafeSingleton instance;

    private ThreadSafeSingleton() {
    }

    public static synchronized ThreadSafeSingleton getInstance() {
        if (instance == null) {
            instance = new ThreadSafeSingleton();
        }
        return instance;
    }
}

In this example, we define a thread-safe Singleton Class called ThreadSafeSingleton. We use the synchronized keyword in the getInstance() method to ensure that only one thread can access the method at a time. This prevents the creation of multiple instances of the class.


♦ Double-checked locking Singleton Class implementation


Another way to make the Singleton Class thread-safe is to use double-checked locking. In this approach, we first check if an instance of the class exists, and if it does not exist, we lock the object to prevent multiple threads from creating new instances of the class.

Example:


public class DoubleCheckedLockingSingleton {
    private static volatile DoubleCheckedLockingSingleton instance;

    private DoubleCheckedLockingSingleton() {
    }

    public static DoubleCheckedLockingSingleton getInstance() {
        if (instance == null) {
            synchronized (DoubleCheckedLockingSingleton.class) {
                if (instance == null) {
                    instance = new DoubleCheckedLockingSingleton();
                }
            }
        }
        return instance;
    }
}

In this example, we define a Singleton Class called DoubleCheckedLockingSingleton that uses double-checked locking to ensure thread safety. We declare the instance variable as volatile to ensure that the value of the variable is always read from the main memory. We use the synchronized keyword to lock the object and prevent multiple threads from creating new instances of the class.


♦ Enum Singleton Class implementation


The Enum Singleton Class is another way to create a Singleton Class in Java. Enums are inherently serializable and thread-safe, and the JVM ensures that only one instance of the enum is created.

Example:


public enum EnumSingleton {
    INSTANCE;

    public void doSomething() {
        // method implementation
    }
}

In this example, we define an Enum Singleton Class called EnumSingleton. The INSTANCE field is the only instance of the class and is created automatically by the JVM. We can access the instance of the class using EnumSingleton.INSTANCE.


Thanks for reading, and happy coding!


Important Java Classes everyone should know -> Understanding Enum in detail in Java

Recent Posts

See All
bottom of page