aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Anonymous classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Anonymous classes" Watch "Anonymous classes" New topic
Author

Anonymous classes

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
hi I have a doubt from here
http://www.geocities.com/swaminr/JavaStudyNotes.htm pertaining to anonymous classes:
May implement an interface,
May extend a class,
ex AddFocusListener(new FocusAdapter(){...})
But cannot do both.
how can anonymous classes implement interfaces
jayashree murugan
Greenhorn

Joined: Feb 10, 2000
Posts: 22
Button mybutton = new Button("hello");
mybutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("anonymous class implementing interface");
}
});
This example shows how the ActionListener interface is being implemented by an anonymous class. Since you can specify
new XXX, the XXX can either be a class that you are extending or an interface that you are implementing, not both.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
I wish to say something on this jayashree.. well you've tried to give clarity about anonymous classes..
Its true that while attaching listener we have to pass an object of any listener interface.. (Its an object of a class who has implemented the interface !)
I object with the line
mybutton.addActionListener(new ActionListener()) // you can not create an object of Interface !!!
Originally posted by jayashree murugan:
Button mybutton = new Button("hello");
mybutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("anonymous class implementing interface");
}
});
This example shows how the ActionListener interface is being implemented by an anonymous class. Since you can specify
[b]new XXX
, the XXX can either be a class that you are extending or an interface that you are implementing, not both.[/B]

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
to add something to anonymous class .. here's the example..
class T extends frame {
T() {
this.addWindowListener(new WindowAdapter() {
public void WindowClosed(WindowEvent we) {
//dispose(); or System.exit(0);
} } );
}
}
WindowAdaper is a class that has implemented the WindowListener interface. ActionListner has got just one method hence not needed to write an Adapter class for that.
We can't create an object of Interface, please be clear with this.
Herbert Maosa
Ranch Hand

Joined: May 03, 2000
Posts: 289
Keyur, You wrote
-----------------------------------------
I object with the line
mybutton.addActionListener(new ActionListener()) // you can not create an object of Interface !!!
-----------------------------------------------------------------
I wonder where you got this from, but you definately got it wrong.It is perfectly legal and normal to create objects of interfaces, and infact necessary.
ComponentListener cmp = new ComponentAdapter() is perfectly legal.You are creating a reference object ,cpm,to the Interface ComponentListener.
JayaShree's illustration about Anonymous classes implementing Interfaces is perfect and use it to learn the fact now.
Herbert.
ARS Kumar
Ranch Hand

Joined: May 22, 2000
Posts: 108
Hi there
Please see http://developer.java.sun.com/developer/Books/certification/page5.html - This has a very good explanation of Anonymous Class's.
Also the following is another from java.sun.com
Anonymous Classes
You can declare an inner class without naming it. Here's yet another version of the now-tired Stack class, in this case using an anonymous class for its enumerator:
public class Stack {
private Vector items;
...//code for Stack's methods and constructors not shown...
public Enumeration enumerator() {
return new Enumeration() {
int currentItem = items.size() - 1;
public boolean hasMoreElements() {
return (currentItem >= 0);
}
public Object nextElement() {
if (!hasMoreElements())
throw new NoSuchElementException();
else
return items.elementAt(currentItem--);
}
}
}
}
Anonymous classes can make code difficult to read. You should limit their use to those classes that are very small (no more than a method or two) and whose use is well-understood (like the AWT event-handling adapter classes).
Hope this helps
ARSKumar

ARS Kumar, Sun Certified Programmer for Java 2 Platform
http://www.automatedsqa.com/
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
hi herbert,
i disagree with u in totality.
this all means that
Interface1 i=new Interface1();
//not allowed
this is allowed
addWindowListener(new WindowAdapter());
//where WindowAdapter is a class not an interface
//hey!!! this is allowed see the example below. i wish i knew how and why this works could anyone explain how a new object can be created from an interface

button1.addActionListener(new ActionListener());
// note ActionListener is an interface not a class
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class demo extends Frame
{
public static void main(String[] args)
{
demo x=new demo();
x.setSize(200,200);
x.show();
System.out.println("Hello World!");
}
demo(){
addWindowListener(new WindowListener(){
public void windowClosing(WindowEvent e){
System.exit(1);
}
public void windowIconified(WindowEvent e){
System.exit(1);
}
public void windowDeactivated(WindowEvent e){
}
public void windowActivated(WindowEvent e){

}
public void windowOpened(WindowEvent e){

}
public void windowDeiconified(WindowEvent e){
}
public void windowClosed(WindowEvent e){
}
});
}
}
[This message has been edited by rahul_mkar (edited May 27, 2000).]
[This message has been edited by rahul_mkar (edited May 29, 2000).]
Herbert Maosa
Ranch Hand

Joined: May 03, 2000
Posts: 289
rahul_mkar,
I observe you disagree with me in totality, oky so let us discuss this. I wrote..
ComponentListener cmp = new ComponentAdapter()
and I said this is very legal.I insist it is. It will be illegal if you dont provide a body for the anonymous class ComponentAdapter(), which I did not do because my point was to show that you can create an object reference to an Interface, which was the topic under discussion.I hope your objection is along those lines otherwise we are talking of different issues.
Herbert.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Herbert I think by the following

ComponentListener cmp = new ComponentAdapter()

you mean that cmp is a object refrence of type ComponentAdapter and ComponenetAdaptor implements the ComponentListtener interface ,hence cmp is also a type of ComponenetListener like the way an object of a subclass is also a type of super class...Am I right..
Thanks
Wali
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
hi herbert
i disagree on u on this statement
"
I object with the line
mybutton.addActionListener(new ActionListener()) // you can not create an
object of Interface !!!
"
which i have given an example which works!!!.
i hope we agree that what u said earlier is indeed true
"
I observe you disagree with me in totality, oky so let us discuss this. I wrote..
ComponentListener cmp = new ComponentAdapter()
and I said this is very legal.I insist it is
"
rahul
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Originally posted by Herbert Maosa:
Keyur, You wrote

----------------
Hi Herber..
isshh.. sorry friends ! That was my mistake with anonymous class..!!! yeh.. anonymous classes have no name.. it must extend some class or an interface.. (so you and jayashree are right here.. ) and the implementation of the rest of the class.
I like your approach and integrity of your knoledge sir !!
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Originally posted by rahul_mkar:
hi herbert,
i disagree with u in totality.
this all means that
Interface1 i=new Interface1();
//not allowed
this is allowed
button1.addActionListener(new ActionAdapter());
//where ActionAdapter is a class not an interface
//hey!!! this is allowed see the example below. i wish i knew how and why this works [b] could anyone explain how a new object can be created from an interface


button1.addActionListener(new ActionListener());
// note ActionListener is an interface not a class
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class demo extends Frame
{
public static void main(String[] args)
{
demo x=new demo();
x.setSize(200,200);
x.show();
System.out.println("Hello World!");
}
demo(){
addWindowListener(new WindowListener(){
public void windowClosing(WindowEvent e){
System.exit(1);
}
public void windowIconified(WindowEvent e){
System.exit(1);
}
//my comments...
/* not necessary to write all these following methods..
public void windowDeactivated(WindowEvent e){
}
public void windowActivated(WindowEvent e){

}
public void windowOpened(WindowEvent e){

}
public void windowDeiconified(WindowEvent e){
}
public void windowClosed(WindowEvent e){
} */
/* check it out friend.. you have written an anonymous class.. not implements an intereface.. you are not in compulson to write all methods of an interface !! */
});
}
}
[This message has been edited by rahul_mkar (edited May 27, 2000).][/B]

------
I have put some comments for you friend !
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
hi keyur,
i agree with u that i have written an anonymous class, but note that ActionListener is not a class it is an interface . i cannot create a interface normally by saying
new ActionListener();
however i am able to do so while creating anonymous classes.
i disagree with u when u say
/* you are not in compulson to write all methods of an interface !! */
indeed u r supposed to write all methods in an interface. if not please tell what is the functionality of adapters.

coming back to the question i posted
an anonymous class
May implement an interface,
May extend a class,
ex AddFocusListener(new FocusAdapter(){...})
But cannot do both.

thus when i say
addWindowListener(new WindowListener())
// i am implementing a interface
addWindowListener(new WindowAdapter())
// i am extending a class
but i cannot do both at one time
hope i can finally clarify things
rahul
Deepa sivasankar
Ranch Hand

Joined: Jul 22, 2003
Posts: 35
Friends,
Please clarify this concept.
You cannot create use new keyword with an interface.
i.e ActionListener al = new ActionListener();
If that is the case , is this allowed if it is an anonymous inner class???. Is this a special case where it's allowed new with an interface.
But i agree the foll. statement as a valid one.
WindowListener wl = new WindowAdapter();
You can assign the reference to an interface of the newly created windowadapter object.
I would appreciate if maha can clarify this for us??
Thanks
deepa
Herbert Maosa
Ranch Hand

Joined: May 03, 2000
Posts: 289
Deepa,
There is no exception to the rule that you can not instantiate an Interface. That is YOU CAN NOT do the following:
ActionListener al = new ActionListener()//Illegal under all circumstaces. Remember that the word new creates an instance of whatever follows it using its constructor.Now this is NOT allowed for interfaces,UNDER ALL CIRCUMSTANCES.After all Interfaces have no constructors.You can however create a reference to an Interface, and pass to it an instance of a class that implements that Interface, this class can be a normal "named" class or an anonymous class.The rules will be the same. Thus you can do:
WindowListener wl = new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
};

Herbert
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Herbert- look back to Jayashree's very first post - the example given there is legal code. It will compile fine if you add the necessary import statements and class structure:
<code><pre>import java.awt.*;
import java.awt.event.*;

public class Test {
public static void main(String[] s) {
Button mybutton = new Button("hello");
mybutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("anonymous class implementing interface");
}
});
}
}</pre></code>
This demonstrates that the anonymous class syntax does allow you to create a class using new and an interface name, provided you supply implementations for all methods of the interface at the time.
Note also that when keyur1401 responded to Jayashree, he (or she?) omitted the body of the class (the braces {} and the stuff inside):
I object with the line
<code><pre>mybutton.addActionListener(new ActionListener()) // you can not create an object of Interface !!!</pre></code>

This created confusion, as it's true that you can't instantiate a class using an interface but no body - but that wasn't the point. The original post showed how to do it using an interface name and a body - and Jayshree was completely correct. Try it if you don't believe it.


"I'm not back." - Bill Harding, Twister
Herbert Maosa
Ranch Hand

Joined: May 03, 2000
Posts: 289
Jim, JayShree
I totally agree with you and everything you are saying. Jim, thanks for emphasizing the point. So then I think Deepa gets the correct answer to his question. I think in essence we are concluding that we can instantiate an Interface, provided that the instance is representing an anonymous class that implements this Interface. Please check my conclusion.
This reminds me of a certain thread about Marcus's mock about whether you can create a reference to an Interface using the new keyword.
Jees, Thanks.
Herbert.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Anonymous classes