This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Anonymous Class of Abstract Class

 
Kathy Hodgson
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Dan Chisolm's mock single subject anonymous classes questions, the first question declares an abstract class A, which has several implemented methods and one abstract method. In class B, an instance of an anonymous class is made which implements that abstract method. The code looks like:
class B {
static A a1 = new A(2){ {incY();}
public int math(){return x() + y()};}
The anonymous class instance is being assigned to a static reference variable. Is that necessary whenever the class whose method is being overridden or implemented in the subclass is abstract? Does the presence of the initializer {incY();} have anything to do with it? And why is this called an instance initializer in the answer and not a static initializer, when the reference variable is static?
Thanks,
Kathy
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kathy,
The static modifier doesn't really need to be there. For this example, perhaps Dan was using it to show something else. When creating an anonymous class, it doesn't require that the variable that references it be static.
And why is the initializer not a static initializer? Well, it doesn't include the keyword static. In order to be a static initializer, it must be in the format "static {...}".
When you're confused by something like this (like whether or not static is required), just try compiling it yourself and see what happens. If you can't explain the results, be sure to post it here.
I hope that helps,
Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic