• 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

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.
 
What are you doing? You are supposed to be reading this tiny ad!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic