aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inner Class Doubts Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Inner Class Doubts" Watch "Inner Class Doubts" New topic
Author

Inner Class Doubts

Micheal John
Ranch Hand

Joined: Nov 01, 2006
Posts: 344
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..


Micheal John
SCJP 1.4 (86%), SCWCD 1.4 (86%), SCBCD 1.3 (85%), SCDJWS (Just Started...) - Satisfaction Lies in Our EFFORT, Not in the ATTAINMENT
Sanjeev Singh
Ranch Hand

Joined: Nov 01, 2006
Posts: 381
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.


~Sanjeev Singh<br />SCJP 1.5
hemadri raju
Greenhorn

Joined: Mar 28, 2006
Posts: 15
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

Joined: Nov 01, 2006
Posts: 381
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

Joined: Nov 10, 2006
Posts: 127
we can use the extra method defined in the anonymous class in follwing possible way...



Hard work rewards
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Inner Class Doubts