Can Java interfaces have constructors? - java

ActionListener is a interface but why can i create instance object?
JButton button = new JButton("Button1");
ActionListener me = new ActionListener(){
public void actionPerformed(ActionEvent ae){
JOptionPane.showMessageDialog(null,ae.getActionCommand());
}
};
button.addActionListener(me);
Or what else? I am not sure. Please help me.

What you're seeing here is called an anonymous class: me will be assigned an instance of an anonymous (un-named) class that implements the ActionListener interface.

Unlike say C#, Java's interfaces cannot prescribe a constructor.
What you are doing in your code is creating an anonymous class that extends java.lang.Object (which does have a default constructor) and implementing the interface.

What you have instantiated is an Anonymous Inner Class. In short, it's an in-line way to both define a class that has no name and instantiate an instance of that class in one statement. You'll only ever be able to refer to anonymous inner classes by the super class they implement or extend. In the case of this question, the super class is the ActionListener interface.
When you compile your code, there will be an extra .class file that exists with a name like this: OuterClass$1.class. That is the class file that represents the anonymous inner class you've defined.
If you want to learn more, check out this section in the JLS http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.5

Because you're implementing the interface with your anonymous class

ActionListener itself is an interface, indeed.
However, the construct in your code is an anonymous inner class, meaning that your interface was implemented by that inner class.

Actually, what you are creating is an anonymous subclass of Object.class that implements the interface. So you are "inheriting" the Constructor from Object, not from the interface.

You are not creating an instance of ActionListener. You are creating an anonymous class which implements ActionListener and you are providing that implementation.

ActionListener is in fact an interface which can not be instantiated.
However, by defining public void actionPerformed() locally you are allowing the interface to act like a class.
This is legal:
ActionListener me = new ActionListener(){
public void actionPerformed(...){...};
};
This is not:
ActionListener me = new ActionListener();

1. You can't have constructor in Interface in java.
2. What you saw here is an Anonymous Class, which is declared and initialized simultaneously, and it must extend or implement a class or interface respectively.

Related

A constructor in an interface?

I’m reading an article about inner class. I found an example that demonstrates anonymous inner class (mentioned below).
button1 = new JButton();
button2 = new JButton();
...
button1.addActionListener(
new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
// do something
}
}
);
According to the example it creates an inner class for responding to a button using ActionListener interface. As I know an interface does not have a constructor. But I’m wondering, how they call a constructor.
"new java.awt.event.ActionListener(){
}"
An interface does not have a constructor, but an anonymous class does: like all classes, it extends java.lang.Object implicitly, therefore it can call the Object's parameterless constructor.
Moreover, Object's constructor is the only constructor you could call, because anonymous classes cannot define custom constructors.
Of course in addition to extending java.lang.Object your anonymous class implements ActionListener - that's why you can pass it to the addActionListener method.
you are constructing a subclass.
Have a quick look at the Java Specification - specifically the Default Constructor Section. You get a constructor because when you instantiate an instance of an interface it would be an Object.
Quote from the spec:
If a class contains no constructor declarations, then a default
constructor with no formal parameters and no throws clause is
implicitly declared.
Anonymous inner class: An inner class with no name.
Now the only detail here we care about is, this new class should subType the interface and for that we provide the necessary method implementations.
The constructor for this class is a default one and performs the job well because there are no instance variables associated.
new java.awt.event.ActionListener(){ }
This statement creates an anonymous class object that implements ActionListener interface.
That is you are invoking anonymous class default constructor not the interface one.
According to java docs
The anonymous class expression consists of the following:
1.The new operator
2.The name of an interface to implement or a class to extend.
3.Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: In the case of implementing an interface, there is no constructor, so you use an empty pair of parentheses.
How are Anonymous (inner) classes used in Java?
http://www.programmerinterview.com/index.php/java-questions/java-anonymous-class-example/
You are not instantiating an interface. You are asking the compiler to create an anonymous class implementing that interface and immediately create an instance of this class.
The best way to demonstrate this is to go to the "class" directory. You will find files of the form className$1.class, className$2.class, etc. These files correspond to those anonymous classes. If you were instantiating the interface itself, there would be no need for these new class files (and the anonymous classes they contain, of course).
That is how Anonymous Classes are(syntax wise).
According to the docs
The anonymous class expression consists of the following:
The new operator
The name of an interface to implement or a class to extend.
Parentheses that contain the arguments to a constructor, just like a
normal class instance creation expression. Note: In the case of
implementing an interface, there is no constructor, so you use an
empty pair of parentheses.
A body, which is a class declaration body. More specifically, in the
body, method declarations are allowed but statements are not.

Must implement the inherited abstract method

My class implements ActionListener. I have implemented the following nested classes below:
JMenuItem mntmNew = new JMenuItem("New...");
mntmNew.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
doNew(e); //calls to outer class for cleaner code
}
});
mnFile.add(mntmNew);
JMenuItem mntmLoad = new JMenuItem("Load...");
mntmLoad.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
doLoad(e); //calls to outer class for cleaner code
}
});
mnFile.add(mntmLoad);
//etc. for the rest of the menu system
However, Eclipse is still telling me that my class must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent e). Can you not implement override methods in a nested class in this way?
Your question:
Can you not implement override methods in a nested class in this way?
The answer is no. Eclipse (actually Java) is complaining that while you're declaring your class as implementing ActionListener you're not giving your class the necessary actionPerformed(...) method in the class's own scope -- and this last part is very important. The class that implements the interface must implement all the interface's required methods in its own scope and not in nested classes. Note that this doesn't prevent you from nesting classes that also implement ActionListener or other interfaces, but regardless, the rule remains that a non-abstract class that implements an interface must override all of the interface's methods.
But since you're not using objects of your class as an ActionListener, the simple solution is to not declare your class as implementing the ActionListener interface. Problem solved. And actually you're far better off not having your GUI class implement your listener interfaces since combining them in one class is asking a class to do too much. In technical terms, it unnecessarily reduces a class's cohesion and risks increasing it's coupling reducing its readability and maintainability.

Is the object of abstract class is created while using anonymous inner class?

Having a little trouble understanding Anonymous Inner classes
Here s the code that I have.I know that WindowAdapter class is an Abstract class, then what does the line "new WindowAdapter()" means? Are we creating an object of WindowAdapter class which is an abstract class.Confused!!!
Class Myframe extends Frame
{
public static void main(String args[])
{
Myframe f=new Myframe();
f.setVisible(true);
f.setSize(300,300);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
It is creating an object of an anonymous class which extends WindowAdapter class without writing the code to subclass it.
From the Java Tutorials:
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name.
This is a shortcut to create an object of a subclass without explicitly writing a separate class which extends WindowAdapter.The point is that you need the object from inside the code of a method so you never refer to them elsewhere, so you don't need to create a separate class for them.
Its no more abstract as you have implemented the abstract method with System.exit(0)
It creates an implementation of WindowAdapter at Runtime and the implementation consists of the code you have provided. It's called anonymous, because it doesn't have a name, therefore you cannot refer it by name. When it's executed once, it cannot be executed again.
You are subclassing the WindowAdapter class and you provide an implementation and instantiate it at the same time. This is what basically happens here.
This is called an anonymous inner class.
As others suggested here the java tutorials are containing excellent explanations about this.
No, you can't create the Object of Abstract Class directly, But you can use an anonymous inner class to do that and you also can implement your own methods inside the anonymous class.
Please refer - http://www.easybix.com/can-create-object-abstract-class/

Why Java interface can be instantiated in these codes? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Creating an “object” of an interface
I am new to Java. Based on my understanding:
We cannot instantiate an Interface. We can only instantiate a class which implements an interface.
The new keyword is used to create an object from a class.
However, when I read the source codes of some Java programs, I found that sometimes an Interface is instantiated. For example:
Example 1:
JButtonObject.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//codes
}
});
Example 2:
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
//codes
}
});
In the example at above, ActionListener and Runnable are both Java interface. May I know why they can be instantiated in these codes?
What is the purpose of instantiating an Interface? Refer to this example, it seems that we should create an instance of a class which implement the interface.
That code does not instantiate an interface, but rather an anonymous class which implements ActionListener or Runnable.
An anonymous class is a local class without a name. An anonymous class
is defined and instantiated in a single succinct expression using the
new operator.
The code is creating an instance of ActionListener anonymously, which means the class does not actually have any name.
After compiling that class, you can see a class YourClass$1.class in the output. The $1 simply means that class is an anonymous class and the number 1 is generated by the compiler. When you have two anonymous classes, it will have something like YourClass$1.class and YourClass$2.class in the compiled classes.
See
Anonymous Classes
Above example does not create new instance of interface - after new keyword there is implementation method for current interface. Read more about anonymous class.
This form is just a shorthand to make it easier to create an object that implements an Interface. It's not the interface itself being instantiated, but rather an Object implements Runnable for example.

How can you instantiate an Interface?

In Swing I'm using ActionListener or any other Listener interface.
In general I can't create object of Interface.
If I use new operator with any constructor name a object is created.
I have a problem with my code below:
jbtOK : is some button object
ActionListener is an interface.
How can I use new ActionListener() in addActionListener method?
Since an object is created. but, I can't create a object from an interface.
Is it only possible in inner classes? i.e, in inner classes I can create objects of interface:
jbtOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("hi");
}
});
with the new keyword you create the object into the memory and as you create the object object of an interface it's need to be implement. lets compare with the explicit class
suppose you define the class which implement this ActionListener interface what you do?
class MyActionListener implements ActionListener{
// now here you need implement all of the method which defined into the ActionListener interface
}
now you can use this class to register listener for Action like this way
jbtOK.addActionListener(new MyActionListener());
this was the explicit implement and as you directly implement it's called Anonymous class as you defined here with ActionListener interface
If I understood your question, you cannot use the methods of an interface, because an interface has all its methods as abstract (empty, without implementation), then you have to implement all the methods requested by your interface.
For example, because you have to add an ActionListener to a button, then associate it to action called in actionPerformed method, you have to declare in the first lines of your code:
public class your_class implements ActionListener
Where the keyword implements is needed to indicate you are implementing the abstract methods of the ActionListener interface, or any other interface, to use these methods with your objects.
http://mindprod.com/jgloss/interface.html#INSTANTIATING:
You can’t instantiate an interface directly, but you can instantiate a class that implements an interface. References to an Object can by via the class name, via one of its superclass names, or one of its interface names.
Read also a few things about anonymous classes.
new class-name ( [ argument-list ] ) { class-body }
It is an anonymous class you are instantiating and passing to your addActionListener method. addActionListener takes an ActionListener as an argument, so since you provide an actionPerformed method it assumes that the anonymous class you pass to it is an ActionListener.
Try to change the name of this actionPerformed method. It will not work anymore since the anonymous class you are passing does not implement the ActionListener Interface. See the error message you get by the compiler.

Categories

Resources