Monday, 23 October 2017

8. Anonymous classes

1. Anonymous classes
  1. Anonymous classes enable you to make your code more concise.
  2. They enable you to declare and instantiate a class at the same time.
  3. 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");
}
  1. 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.
  2. The anonymous class expression consists of the following:
    1. The new operator
    2. The name of an interface to implement or a class to extend.
    3. 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.
    4. A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
  3. An anonymous class has access to the members of its enclosing class.
  4. An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.
  5. You cannot declare static initializers or member interfaces in an anonymous class.
  6. An anonymous class can have static members provided that they are constant variables.
  7. can declare the following in anonymous classes:
    1. Fields
    2. Extra methods (even if they do not implement any methods of the supertype)
    3. Instance initializers
    4. Local classes

No comments:

Post a Comment

3. Java Program to create Binary Tree