This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Accessing enclosing class method from inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Accessing enclosing class method from inner class" Watch "Accessing enclosing class method from inner class" New topic
Author

Accessing enclosing class method from inner class

richard rehl
Ranch Hand

Joined: May 21, 2007
Posts: 36
A question: in the following code, taken from SB6 Chapter 8 Self Test, I understand how to access the enclosing class method drive() from the inner class constructor and the initializer block.
but if I make a new instance of the enclosing class from within the inner class, I'm confused as to why I can't call the same method using that reference.
Simran Dass
Ranch Hand

Joined: Jan 09, 2010
Posts: 183

It will work if you call it from some block or method. Whether its an inner class or whatever you cannot call methods in a class where you can make only declarations or define methods.
I have added a works method and called c.drive() from there.

Simran Dass
Ranch Hand

Joined: Jan 09, 2010
Posts: 183


What I mean is you cannot do this -

class A{

B bb = new B();
bb.go(); // THIS IS WRONG

}

class B{

void go(){}

}


 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Accessing enclosing class method from inner class
 
Similar Threads
inner classes
Order of Execution(Interesting)-:)
not an enclosing class
Inner Classes and the word 'this'- Chapter 8 Question 9 page 697
method-local inner class problem