Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Anonymous inner class  RSS feed

 
Kaz Yosh
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Kaz Yosh
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!