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

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.

Related

How does this Java code instantiate an abstract class?

I am making changes to a Java class of ours, and I noticed the following line of code:
OurClass<OurInterface1> ourClass = new OurClass<OurInterface1>() {};
What I find strange about that line is that OurClass is an abstract class - here's the definition of OurClass:
public abstract class OurClass<T extends OurInterface1> implements OurInterface2<T>
When I remove the {} at the end of the line, Eclipse tells me Cannot instantiate the type OurClass<OurInterface1>, but when I put the {} back, everything is OK.
How does {} allow you to instantiate an abstract class?
Adding the {} introduces the syntax for an anonymous inner class.
The anonymous class expression consists of the following:
The new operator
The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.
Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
You are declaring an anonymous inner class that subclasses OurClass. The body of this class is empty: {}. This anonymous inner class is not abstract, so you are able to instantiate it.
When you remove the {}, the compiler thinks that you are directly instantiating OurClass, an abstract class, so it disallows it.
You can actually extend and override methods on the fly when you instantiate off an interface or extendible class. This is called an anonymous inner class.
What you did in your example is create an anonymous inner class, but it had no effect because you didn't override anything. You could have put overridden methods in those curly brackets {}.
OurClass<OurInterface1> ourClass = new OurClass<OurInterface1>() {};
A commonly applied use of anonymous inner class is on the Runnable interface, which defines a single void run() method. You can implicitly instantiate an object that implements Runnable and override run() on the fly.
Runnable someTask = new Runnable() {
#Override
public void run() {
System.out.println("Running a task!");
}
};
Anonymous inner classes are disliked by a lot of developers because they are pretty verbose. Fortunately in Java 8, you can use lambda expressions to replace most anonymous inner classes that implement a single method. The compiler infers the anonymous inner class for you basically, allowing you to write the code more concisely.
Runnable someTask = () -> System.out.println("Running a task!");
The block after the call to the new operator (new OurClass<OurInterface1>() {}) is infact creating an instance of an anonymous class which extends OutClass.
Since this class is no longer abstract, there's no problem to instantiate it.
You cannot instantiate an abstract class without implementing the abstract functions within the class. This is usually done by instatiating abstract classes with implemented class.
Refer: https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
In your case, the {} used after the instantiation allows you to implement any of the abstract functions in the abstract class.
For example,
Consider
public abstract class DummyClass {
abstract void test() ;
}
is the abstract class with a abstract function.
The class can be initiated by:
DummyClass d = new DummyClass(){
void test(){
//test() implementation here
}
} ;
Hope this helps! :)

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/

Can Java interfaces have constructors?

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.

Instantiating Java object with a passed in method

It's been a few years since I've been heavily into Java. Coming back to it I'm seeing this pattern all over the place:
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
// do work
}
});
This looks more like Functional programming to me. It's a nice pattern but how is it possible to pass a method like this? In the old days a class was a class, and once compiled there was little you could do to it.
My questions are:
Can anyone let me know what this pattern is called?
How can I write a class that can be instantiated in this way.
Are there any other useful examples of functional patterns that have made their way into Java?
What do I need to Google to read more about this?
Thanks.
This passes an anonymous class, not a method.
This is a typical pattern, not just in Swing programming, but anywhere you need (hopefully) short, "throw-away" implementations of an interface or class that doesn't need to be re-used, instead of creating a full-blown implementation.
Any class/interface can be instantiated like this, there's nothing special about it:
public interface Foo {
String foo();
}
...
public class Main {
public static void main(String[] args) {
System.out.println(new Foo() {
public String foo() {
return "plugh";
}
});
}
}
Anonymous inner classes get their own class files, too, even though their source is embedded.
In this example, a Main$1.class file will be generated for the anonymous inner class, in addition to the expected Main.class file.
The statement: new OnRatingBarChangeListener() creates a new instance of a class. The following part inside the curly braces is the definition of the class.
In this case that class in an anonymous class that implements the named interface.
Anonymous classes are classes, that are declared without a name, and thus, can not be used like regular named classes.
This pattern is very common when using listeners, that often contain only a single to a few methods that do an almost trivial task.
This is the Listener pattern. Rating bar takes an implementation of OnRatingBarChangeListener and calls its onRatingChanged method on the appropriate event.
You can use instance of any class which implements OnRatingBarChangeListener. So you can use either a named class of your own or you can pass it an anonymous class like in the example. The anonymous class in the example is effectively a unnamed class which extends Object and implements OnRatingBarChangeListener. Since the class isn't named it cannot be referenced and so the instance passed is the only instance existing.
This is called "Observer pattern". A good example for this is adding action listeners for java button or other component. For example,
myButton.addActionListener(
new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Work here
}
});
In here "myButton" is the subject and ActionListener is the observer.

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