This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Anonymous Class of Abstract Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Anonymous Class of Abstract Class" Watch "Anonymous Class of Abstract Class" New topic

Anonymous Class of Abstract Class

Kathy Hodgson

Joined: Jun 16, 2003
Posts: 28
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?
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
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,

SCJP Tipline, etc.
I agree. Here's the link:
subject: Anonymous Class of Abstract Class
It's not a secret anymore!