• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

K&B Chapter8-Inner classes-Q 8

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

Can anybody please explain the working of the below code?not clear with the syntax " (new Bar() {}).go();"

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

Thank you
Maya
 
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
it is nothing else than 'Anonymous Inner Class'...
you are creating a sub class of Bar at runtime ( obviously it is not having any name and not overriding go() method)
so when you say
(new Bar(){}) is creation of subclass and its instance as well...
and when you call go() method over that instance , the go method of parent will be called...
again if you have putted as bellow



then new overridden method would be called

 
Maya Karthik
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much Vijay.I got it.
 
reply
    Bookmark Topic Watch Topic
  • New Topic