This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Initializer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Initializer" Watch "Initializer" New topic
Author

Initializer

Anuji Philip
Ranch Hand

Joined: Feb 25, 2002
Posts: 46
In Mughal(p:263) example on initializers;
class Base
{
int a; int b;
void print()
{
System.out.println("a="+a);
}
}
class AnonClassMaker
{
Base creatAnon()
{
return new Base()
{
{
a = 5;b=10;
}
void print()
{
super.print();
System.out.println("b="+b);
}
};
}
}
public class InstanceInitBlock
{
public static void main(String args[])
{
new AnonClassMaker().creatAnon().print();
}
}
Output : a=5 b=10
I am not getting how a=5.my idea was a =0.
R K Singh
Ranch Hand

Joined: Oct 15, 2001
Posts: 5371
let me try to explain this :
I think u got this that creatAnon() is returning an annonymous class which extends Base.
This extended class has initializer block which initializes a & b which are being inherited from class Base.
So when super.print() is called then it uses initialized a, which is 5 as they have only one copy of members.
HTH
CMIW
[ March 18, 2002: Message edited by: Ravish Kumar ]

"Thanks to Indian media who has over the period of time swiped out intellectual taste from mass Indian population." - Chetan Parekh
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Initializer