Can I use anonymous inner class to implement a interface?

B

Bruce Sam

I have tried several times,but can't find a method to implement
it.Could you give me some advice?
 
M

Mike Schilling

Bruce Sam said:
I have tried several times,but can't find a method to implement
it.Could you give me some advice?

The syntax is

new interfaceName() { ...method defs }

The class created is always a subclass of Object.

For instance, to implement a simple Comparator:

Comparator comp = new Comparator()
{
public Compare(Object o1, Object o2)
{
return o1 = o;
}
}

This creates an anonymous subclass of Object that implements Comparator.
 
R

Ryan Stewart

Mike Schilling said:
The syntax is

new interfaceName() { ...method defs }

The class created is always a subclass of Object.

For instance, to implement a simple Comparator:

Comparator comp = new Comparator()
{
public Compare(Object o1, Object o2)
{
return o1 = o;
}
}

This creates an anonymous subclass of Object that implements Comparator.
Except that
1) The method's name is "compare";
2) The compare method returns an int;
3) Your return statement
a) won't compile,
b) wouldn't do what you want if it did, and
c) would be the wrong return type even if it did what you want; and
4) You need a semicolon after the final brace.

Properly written, it would be:
Comparator comp = new Comparator() {
public int compare(Object o1, Object o2) {
return 0; // This will make all objects passed to this Comparator equal
}
};
 
B

Bruce Sam

Thanks Schilling,I have a follow question.How to access the method
Compare( ) that in this anonymous inner class?
 
R

Ryan Stewart

Bruce Sam said:
Thanks Schilling,I have a follow question.How to access the method
Compare( ) that in this anonymous inner class?
comp.Compare(o1, o2), though it should be "compare" as per my other post.
 
M

Mike Schilling

Ryan Stewart said:
Except that
1) The method's name is "compare";
2) The compare method returns an int;
3) Your return statement
a) won't compile,
b) wouldn't do what you want if it did, and
c) would be the wrong return type even if it did what you want; and
4) You need a semicolon after the final brace.

Properly written, it would be:
Comparator comp = new Comparator() {
public int compare(Object o1, Object o2) {
return 0; // This will make all objects passed to this Comparator
equal
}
};

You'd think that by now I'd know to try something before posting it
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top