Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner Class Doubts

 
Micheal John
Ranch Hand
Posts: 344
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From K&B Book


What is the meaning of (new Bar() {})? why the open and close curly braces {}? whether it has any meaning?

(new Bar() {}).go();

And don't find any differences in the o/p, when i have used like:

(new Bar()).go();

or

Bar b = new Bar();
b.go();

Just want to know why {} is added? I thought of invalid syntax..
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Micheal John writes....
What is the meaning of (new Bar() {})? why the open and close curly braces {}? whether it has any meaning?

&
And don't find any differences in the o/p.

There is a concept of anonymous inner class in Java which is in picture here.
new Bar(){} is a instance to anonymous inner class which is a subclass of Bar with no extra methods added or overrided.
 
hemadri raju
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are actually subclassing the Bar class in when you write the code like Bar{} which can be well understood by executing the following program.

following the sample program with small addition to your code.


public class Foo{
Foo(){System.out.println("foo");}

class Bar{Bar(){System.out.println("bar");}

public void go(){System.out.println("hi");}
}

public static void main(String args[]){
Foo f = new Foo();
f.makeBar();
}
void makeBar(){
(new Bar(){public void go(){System.out.println("hello world");}}).go();
}
}
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hemadri rajy writes...
(new Bar(){public void go(){System.out.println("hello world");}}).go();

THis is perfectly true.
One small add..+
It is valid to add extra method in the anonymous body like

but calling like b.go2() will give a compilation error.
 
Bob CHOI
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
we can use the extra method defined in the anonymous class in follwing possible way...

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic