Witscale Test Center

4.7 Anonymous inner class > 4.7.2 Passing arguments to superclass constructors


4.7.2 Passing arguments to superclass constructors

Anonymous class is a class without any name. Hence, it cannot define constructors of its own as constructors of a class need to have the same name as the class. But anonymous class can use the constructors of its superclass to pass arguments. These arguments are passed at the time of construction itself. For example, if the Bicycle class has constructor which takes String argument as:

 

class Bicycle{

      private String make;

       public Bicycle(String make) {

         this.make = make;

       }

       public void paddle() {

           System.out.println(“paddling”);

       }

 

}

You can create an anonymous class by extending Bicycle and by passing arguments to Bycycle’s constructor as:

 

Bicycle mountainBike = new Bicycle(“Trek”) {

       public void paddle() {

           System.out.println(“paddling”);

       }

};

 

At the construction of anonymous class’s instance in new Bicycle(“Trek”){}, the superclass Bicycle’s constructor gets called and make is assigned a value, “Trek”.