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 Anonymous inner class 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 "Anonymous inner class" Watch "Anonymous inner class" New topic
Author

Anonymous inner class

Kaz Yosh
Ranch Hand

Joined: May 22, 2003
Posts: 63
Hi all,
This is from Osbone java2 certified programer and developer book chapter 8 selftest question 8;
class SCJP{
SCJP(){System.out.println("scjp");}
class Bar{
Bar(){System.out.println("bar");}
public void go(){System.out.println("hi");}
}
public static void main(String [] kaz){
SCJP scjp = new SCJP();
scjp.makeBar();
}
void makeBar(){
(new Bar(){}).go(); //Line 1
}
}
I want to make sure my understanding here.
On line 1,anonymous class is instantiated with empty method implementation so it does not override any method in the super class which is class Bar. In this case, line 1 just use super class's constructor to build itself since this anonymous class is in fact a subclass of Bar. It can be thought of as hidden super() inside the body of anonymous class. am I still on the right track?


"If anything can go wrong, it will"
Kaz Yosh
Ranch Hand

Joined: May 22, 2003
Posts: 63
By the way, I changed the class name so that I can run different code over and over on my IDE. Just so you know.
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
You are definitely in the right track.
To check it out use javap with the local class SCJP$1:

SCJP$1 declares a constructor SCJP$1(SCJP). Inside it the argument SCJP is passed to the call of the super constructor SCJP.Bar(SCJP). Also it is stored in an automaticlly spawned field called this$0. Through this reference the instance of the local class can access the members declared in the outer class.


SCJP2. Please Indent your code using UBB Code
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Anonymous inner class