Java - General » J2SE » Interface
383 Views
8 Replies
Interface
Posted 15-06-2009Reply
Can we create object of interface..?
yes sure.
her's an AWT example
Button closingButton = new Button("CLOSE");
closingButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae){
System.exit(0);
}
}
);
Its an example of anonymous inner class.
actually its a trick, its not an object of ActionListener interface but an object of the class (implicitly) implementing ActionListener. But simply it looks as "new ActionListener()" thats y i said yes!!!
By the way, interfaces are implicitly abstract, they cannot be directly instantiated. Interfaces are special to java, as they provide so many features to java,
1) Polymorphism.
2) multiple inheritance (as a class can implement zero or more interfaces & an interface can extend zero or more interfaces)
3) Function callback.
4) Marker interface.(java.lang.Cloneable, java.io.Serializable, java.rmi.Remote these interfaces are marker interfaces)
...... and much more..
Regards Swapnil.
her's an AWT example
Button closingButton = new Button("CLOSE");
closingButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae){
System.exit(0);
}
}
);
Its an example of anonymous inner class.
actually its a trick, its not an object of ActionListener interface but an object of the class (implicitly) implementing ActionListener. But simply it looks as "new ActionListener()" thats y i said yes!!!
By the way, interfaces are implicitly abstract, they cannot be directly instantiated. Interfaces are special to java, as they provide so many features to java,
1) Polymorphism.
2) multiple inheritance (as a class can implement zero or more interfaces & an interface can extend zero or more interfaces)
3) Function callback.
4) Marker interface.(java.lang.Cloneable, java.io.Serializable, java.rmi.Remote these interfaces are marker interfaces)
...... and much more..
Regards Swapnil.
Basically you can't create object of an interface.
The reason behind is that interface contains only method's declaration and not definition.
If you want to create object of interface, then you need to define its methods as shown by swapnilkumar.
But I have one question that we have several interface in Java those don't have any method, in that case can we create object of that interfaces in the way swapnilkumar created?
The reason behind is that interface contains only method's declaration and not definition.
If you want to create object of interface, then you need to define its methods as shown by swapnilkumar.
But I have one question that we have several interface in Java those don't have any method, in that case can we create object of that interfaces in the way swapnilkumar created?
















