• Post Reply Bookmark Topic Watch Topic
  • New Topic

Anonymous Class Body Rules  RSS feed

 
Carol Murphy
village idiot
Bartender
Posts: 1211
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code snippet is from Oracle's tutorial for Java 7. I don't understand what the last line is trying to say about the body of the anonymous class expression. It says method declarations are allowed in the body, but statements are not. Isn't this first line in the body block( String name = "tout le monde"; )considered a statement?

Consider the instantiation of the frenchGreeting object:

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);
}
};

The anonymous class expression consists of the following:

The new operator

The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.

Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: In the case of implementing an interface, there is no constructor, so you use an empty pair of parentheses, like in this example.

A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37513
554
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Carol,
Technically that line is a declaration

As an example, this code doesn't compile.


But this code does:
 
Carol Murphy
village idiot
Bartender
Posts: 1211
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, I need to pay attention to the difference between statements and declarations! But there is a statement inside the class body declaration, inside the implementation of the method greetSomeone(). So I'm assuming a block inside the body of the class declaration can contain a statement if it appears inside of a method declaration, like this one:

public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}

Is my assumption correct?

The precise usage of terminology really confuses me sometimes!
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37513
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. The rules go by only one level out. So a method contains the same things regardless of whether it is in an abstract class or an anonymous class or whatever else.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!