Witscale Test Center

4.7 Anonymous inner class > 4.7.3 Modifiers and anonymous class


4.7.3 Modifiers and anonymous class

We have seen that anonymous classes are declared and constructed at the same time and hence has only one instance. They (their definition) cannot be reused which means you cannot create instances or extend an anonymous inner class. Interestingly, you can  assign an instance of anonymous class to a member variable. For example,

 

public class CampingGear {

      String aTent ="Eureka";

      private Bicycle myBike = new Bicycle("Trek") {};

}    

 

Note that the anonymous class new Bicycle() {} is not a member class. The variable myBike is a private member which stores a reference to an instance of an anonymous class. Anonymous classes are type of  local inner classes. Therefore access modifiers are not applicable to anonymous classes. For the same reason, they can never be declared as abstract or static. If you think for a while, you may notice that an anonymous class is always implicitly final, as it cannot be subclassed further.

Now that we have seen all declaration issues of anonymous class, its time to see which variables it can access.