Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner class question

 
Kannan Raju
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


My question for the above code is, what is the significance of {} at the place I marked //here. It is not creating an anonymous class. It is printing the same result with the {} and without the {}. I think it has been place there to confuse us. Please let me know. Thx.
 
samdeep aarzoo
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
firstly it is not an anonymous class

as in anonynous class
code must be like this new Bar(){};
In anonymous class semicolon must be after the second curley braces
and here it is (new Bar(){}).go();


It is printing the same result with the {} and without the {}


and about this u can write anywhere {} in code
this will compile as comiler check matching braces
 
Joe Sondow
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by bikash mittal:
firstly it is not an anonymous class

as in anonynous class
code must be like this new Bar(){};
In anonymous class semicolon must be after the second curley braces
and here it is (new Bar(){}).go();


That's incorrect. new Bar() {} is an anonymous class. The semicolon does not need to be immediately after the declaration of the anonymous class. What is true is that a statement where an anonymous class is created and instantiated must end in a semicolon, which this statement does. However, that does not mean that the semicolon must occur immediately after the anonymous class declaration.

(new Bar() {}).go();

That statement ends in a semicolon, as it should.

The significance of the {} in that statement is that it tells the compiler to create an anonymous class that is a subclass of Bar, and to instantiate that anonymous class. If you wanted to, you could have added code inside the braces to alter the functionality of the anonymous class. For instance, you could have overridden the go() method in the anonymous class like this:



The reason that the behavior of

(new Bar() {}).go();

matches the behavior of

(new Bar() ).go();

is that the anonymous class you created does not implement any changes from its superclass, Bar. The anonymous class inherits the public method go() from Bar, and therefore the program produces the same output in both cases. Try overriding the go() method inside the braces to see a change take place in the output.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic