This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Nested classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Nested classes" Watch "Nested classes" New topic

Nested classes

Sharanya Sharma
Ranch Hand

Joined: Jul 26, 2004
Posts: 54

This is one of the question in nested classes of K&B

public class Foo
Foo() {System.out.print("Foo");}
class Bar{
Bar() {System.out.print("Bar");}
public void go() {System.out.print("Hi");}
public static void main(String args[]){
Foo f = new Foo();
void makeBar(){
(new Bar() {}).go();

The result of the above code is given as "FooBarHi".

But as the makeBar method, while invoking new Bar(){} it is creating a new empty subclass of Bar class rather than invoking the constructor of Bar class. As the go() method is invoked on anonymous empty subclass, it should give a compile error.

Please clarify me if I have interpreted the code wrongly or if my assumption is wrong.

kavya krushi
Ranch Hand

Joined: Oct 25, 2000
Posts: 48

The object created in the makeBar() method is an instance of anonymous "subclass" of Bar. Since you did not override the go() method, it will be inherited from the parent class.

Kavya Krushi
[ July 28, 2004: Message edited by: kavya krushi ]
Sharanya Sharma
Ranch Hand

Joined: Jul 26, 2004
Posts: 54
Thanks for the reply. I think I was carried away with the concept of anonymous nested class to consider the basic subclass theory.
I agree. Here's the link:
subject: Nested classes
Similar Threads
Inner Classes
K&B Chapter8-Inner classes-Q 8
Inner Classes Mock question doubt 3
Doubt in Nested Inner Class
K&B chapter 8 Self Test Q 8