aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Anonymous Classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Anonymous Classes" Watch "Anonymous Classes" New topic
Author

Anonymous Classes

Sharath Sri
Greenhorn

Joined: Dec 01, 2007
Posts: 8
Hi All,
In one of the books I'm refering to for SCJP1.5 says that the anonymous classes can contain only final static fields. But when I tried the below program it actually executed.
class Boo
{
Boo(String s){}
Boo(){}
void method()
{
}

}
class Bar extends Boo {
Bar(){}
Bar(String s){super(s);}
public static void main(String args[])
{
Boo f = new Boo(){String s;
void mehtod()
{
s= "20";
}
};
}
}
Is it that I'm not reading the statement properly or the book is wrong.
Please correct me if I'm wrong.
Regards,
Sharath
Preeti Yarla
Ranch Hand

Joined: Sep 08, 2007
Posts: 69
Any inner class, with the exception of static inner class, cannot contain any static declarations.


SCJP
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
In your example, you inner class contains an instance variable. What the book is saying is that the inner class cannot have a member declared static unless it is final and static making it a compile-time constant.
prajal Mehta
Ranch Hand

Joined: Dec 03, 2007
Posts: 66
What the book is saying is that the inner class cannot have a member declared static unless it is final and static making it a compile-time constant.

Do you mean , we can declare a varaible marked Static Final in an inner class.

I tried following code and compiler is giving errors-- field can not be declared static--

Deepak Jain
Ranch Hand

Joined: Aug 05, 2006
Posts: 637
First Remeber
a) Inner classes [Regular, Method local, Anonymous] cannot have static methods and cannot have static variables.
However they can have PRIMITIVE COMPILE TIME CONSTANTS i.e., static and final primitives and not objects, Further like other COMPILE TIME CONSTANTS that you create in your inner class or for that matter any other class must be initialized with a value when they are declared or else the compiler will crib.
Since your code s is a String object it fails to compile, Inner classes can only have PRIMITIVE final static fileds.
So your code cannot be fixed unless s is declared as primitive.
I hope that clears the confusion.
Thanks
Deepak


SCJP, SCWCD, SCBCD
Deepak Jain
Ranch Hand

Joined: Aug 05, 2006
Posts: 637
Correction:
Innerclasses {Inner, Method local and anonymous} classes can have static variables only {primitive or object} provided they are marked final which are called compile time constants {final and static variables}.
Code demonstrates this.

Thanks
Deepak
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Anonymous Classes