1. Anonymous classes
- Anonymous classes enable you to make your code more concise.
- They enable you to declare and instantiate a class at the same time.
- They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
interface HelloWorld {
public void greet();
public void greetSomeone(String someone);
}
public static void main(String... args) {
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
frenchGreeting.greetSomeone("Fred");
}
|
- The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code.
- The anonymous class expression consists of the following:
- The new operator
- The name of an interface to implement or a class to extend.
- Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
- A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
- An anonymous class has access to the members of its enclosing class.
- An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.
- You cannot declare static initializers or member interfaces in an anonymous class.
- An anonymous class can have static members provided that they are constant variables.
- can declare the following in anonymous classes:
- Fields
- Extra methods (even if they do not implement any methods of the supertype)
- Instance initializers
- Local classes
No comments:
Post a Comment