• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Anonymous Classes

 
Sharath Sri
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any inner class, with the exception of static inner class, cannot contain any static declarations.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Deepak Jain
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic