top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What are different types of anonymous classes in JAVA, Please explain with an example?

+1 vote
501 views
What are different types of anonymous classes in JAVA, Please explain with an example?
posted Feb 27, 2015 by Amit Kumar Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Plain old anonymous class type one–

class superClass{
    void doSomething() {
      System.out.println(“Doing something in the Super class”);
    }
}
class hasAnonymous{
    superClass anon = new superClass(){
    void doSomething() {
      System.out.println(“Doing something in the Anonymous class”);
    }
};

Here anon is the reference which is of type superClass which is the class extended by the anonymous class i.e. superclass of the anonymous class. The method doSomething() is the super class method overridden by the anonymous class.

Plain old anonymous class type two –

interface Eatable {
  public void prepareSweets();
}
class serveMeal {
    Eatable food = new Eatable(){
    public void
        prepareSweets(){ //come implementation code goes here }
    };
}

food is reference variable of type Eatable interface which refers to the anonymous class which is the implementer of the interface Eatable. The anonymous implementer class of the interface Eatable implements its method prepareSweets() inside it.

Argument defined anonymous class –

interface Vehicle {
    void getNoOfWheels();
}
class Car {
    void getType(Vehical v) { }
}
class BeautifulCars {
    void getTheBeautifilCar() {
        Car c = new Car ();
        c.getType (new Vehicle () {
            public void getNoOfWheels () {
                System.out.println("It has four wheels");
            }
        });
    }
}

Anonymous class is defined as the argument of the method getTheBeautifilCar(), this anonymous class is the implementer of the interface Vehicle. The method of class Car getTheBeautifilCar() expects the argument as an object of type Vehicle. So first we create an object of Car referenced by the variable ‘c’. On this object of Car we call the method getTheBeautifilCar() and in the argument we create an anonymous class in place which is the implementer of interface Vehicle hence of type Vehicle.

answer Feb 28, 2015 by Kali Mishra
...