This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initializer

 
Anuji Philip
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic