• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Nested classes

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

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();
f.makeBar();
}
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.

Thanks
Sharanya
 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sharanya,

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
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the reply. I think I was carried away with the concept of anonymous nested class to consider the basic subclass theory.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic