iTestee Java,Theories Anonymous Classes

Anonymous Classes

What is an Anonymous Class in Java?

An anonymous class in Java is a class without a name that is declared and instantiated in a single expression.

It’s a shortcut to create a subclass or an implementation of an interface without explicitly writing a new class file.

It’s often used to override methods of a class or interface on the fly.

When to Use?

  • When you need a one-time use class.
  • When the class is not reused elsewhere.
  • Commonly used with event listeners, threads, or callback implementations.

Example with a Classes





/// /For named cass sample
abstract class Person{

    abstract void JobRole();

}

// extends from the Person class to override the JobeRole
class Customer extends Person{

    @Override
    void JobRole() {
        System.out.println("Job Rol");
    }
}

// Sample to call the super class
abstract class Animal{

    abstract void run();

    String eat(){
        return "Eat";
    }
}

public class Main {
    public static void main(String[] args) {

        // Customer override its JobRole through Named class
        Customer customer = new Customer();
        customer.JobRole();

        //Supplier override its JobRole through Anonymous class
        Person supplier = new Person() {
            @Override
            public void JobRole() {
                System.out.println("Supplier Job Rol");
            }
        };

        supplier.JobRole();


        // calling the super class via Anonymous class
        Animal dog = new Animal() {
            @Override
            public String eat() {
                System.out.println("Dog eat");
                System.out.println(super.eat());
                return "Test done";
            }

            @Override
            public void run() {
                System.out.println("Dog run");
            }
        };

        System.out.println(dog.eat());


    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 57 = 66
Powered by MathCaptcha