As the name suggests, there is no name for the internal class. On the surface, they seem to have names, but they are not actually their names. An anonymous internal class is an internal class without a name. Under what circumstances do I need to use an anonymous internal class? If the following conditions are met, it is appropriate to use an anonymous internal class:
· Only use one instance of the class.
· Classes are used immediately after definition.
· The class is very small (Sun recommends following four lines of code)
· Naming classes does not make your code easier to understand.
When using anonymous internal classes, remember the following principles:
· No constructor is allowed for anonymous internal classes.
· Anonymous internal classes cannot define any static members, methods, and classes.
· Anonymous internal classes cannot be public, protected, private, or static.
· Only one instance of the anonymous internal class can be created.
· An anonymous internal class must be behind New and be used to implicitly implement an interface or implement a class.
· Because the anonymous internal class is a local internal class, all restrictions on the local internal class take effect.
A. inherited anonymous internal class
public class Car { public void drive(){ System.out.println("Driving a car!"); } public static void main(String[] args) { Car car = new Car(){ public void drive() { System.out.println("Driving anther car!"); } }; car.drive(); } }
The result is output: driving another car! The car reference variable is not a reference car object, but an object of the car anonymous subclass.
B. Interface-Based Anonymous internal class.
interface Vehicle { public void drive(); } class Test{ public static void main(String[] args) { Vehicle v = new Vehicle(){ public void drive(){ System.out.println("Driving a car!"); } }; v.drive(); } }
The code above is strange, as if it is instantiating an interface. This is not the case. An interface-Based Anonymous internal class implements an interface-Based Anonymous class. Only one interface can be implemented.
C. Parameter-Based Anonymous internal class.
class Bar{ void doStuff(Foo f){} } interface Foo{ void foo(); }
class Test{ static void go(){ Bar b = new Bar(); b.doStuff(new Foo(){ public void foo(){ System.out.println("foofy"); } }); } }