This question already has answers here:
How are Anonymous inner classes used in Java?
(18 answers)
Closed 3 years ago.
While creating threads I see code like:-
Runnable watdaheck = new Runnable()
{
System.out.println("java with time contradicts itself");
}
From what I know an interface cannot be instantiated so I fail to understand how we can write Runnable() for creating anonymous class. An interface can be given a reference but cannot be instantiated is what we are taught in polymorphism.
Runnable is interface, you are creating an anonymous class which implements the Runnable interface.
I just modify a bit your code.
Runnable watdaheck = new Runnable()
{
public void run(){
System.out.println("java with time contradicts itself");
}
}
The right part
new Runnable()
{
public void run(){
System.out.println("java with time contradicts itself");
}
}
is an instance of an anonymous class that implements interface Runnable
The left part Runnable watdaheck, watdaheck is a reference that refers to above object.
Your code is same with below code:
class SubRunnable implements Runnable{
public void run(){
//do something
}
}
Runnable r = new SubRunnable();
You should read more about anonymous class in Java. https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
Runnable is an interface. We use it with the "new" operator in order to create an anonymous class object whICH
Related
Could someone explain what does this code does? new Thread(new X()).start();
Rest of the code:
class X implements Runnable {
X() {}
}
public static void main(String[] arg) {
new Thread(new X()).start();
}
}
This is a very simple example, which shows how to create a new thread and run it. When you create new threads in Java, you give them something to do - a "Runnable".
class X implements Runnable
This interface has only one method - run(). So you create a new thread, with a runnable in its' constructor.
new Thread(new X())
Once you have created a new thread, you have to start it with the start() method. This is when it calls the runnable's run() method. In your example, this has just been chained on after the construction of the thread:
new Thread(new X()).start();
Now, this example is unusual in that class X doesn't actually implement the run method. But normally, there's that extra bit, so your example would look like this:
class X implements Runnable {
public void run() {
System.out.println("This is running on a different thread!");
}
public static void main(String[] arg) {
new Thread(new X()).start();
}
}
You don't need to define a constructor if it's blank, first of all. It'll automatically be blank if you don't define one. Second of all, you can simply do an anonymous class definition, which I'll explain in a second. The method isn't main in this case, it's run. You can define a thread object using the anonymous class definition, too.
new Thread() {
#Override
public void run() {
//Code here
}
}.start();
The anonymous class definition allows you to define and instantiate a class which extends/implements another class both at the same time without actually creating the class. Also, note that X.main() is static, meaning that any instance of X will not have that method. You want to override run and call start. Start is just a method which calls run in a different thread. Note that you can't start a thread twice.
Every thread object has a method run(). if you call the start() method of thread object, then it will execute run().
The only difference is it will be executed separately/parallely and won't be in the existing sequence of operation.
You can create thread in two ways : one by extending Thread and other by implementing Runnable interface.
If you are not extending the Thread class,your class object would not be treated as a thread object. So you have to explicitly create Thread class object.
Thread class will take Runnable class as parameter in constructor.
You are passing the object of your class X that implements Runnable to Thread constructor so that your class run() method will be executed from start() method of Thread.
You can create threads in two different ways. Have a look at oracle documentation about thread creation
An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this:
Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I run into some code which contains anonymous classes. I haven't met with anonymous classes before, so I did some research on them.
My main area of interest is java, so I checked Oracle's tutorial of anonymous classes. I understand the mechanism and I see the point of the examples but in my opinion using anonymous classes makes the code hard to read and can cause a lot of headache.
Are there any cases when it is unavoidable to use anonymous classes or it is advised to use them instead of named classes?
Are there any cases when it is unavoidable to use anonymous classes
No, you can always just use a private inner class instead of an Anonymous class.
using anonymous classes makes the code hard to read and can cause a lot of headache
This very much depends on how you use anonymous classes. Consider the following example:
new Thread(new Runnable() {
#Override
public void run() {
// do something
}
}).start();
In this example you create a Runnable which is run by a thread. If you wouldn't use an anonymous class you'd have to write it as follows:
private class SomeClass implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
}
}
and use it as:
new Thread(new SomeClass()).start();
With the first possibility you can directly see what that thread is doing, in the second possibility you'll first have to find the class that is used here.
Another advantage of anonymous classes. You can do the following:
// define some constant which can be used in the anonymous class:
final String someStr = "whatever";
new Thread(new Runnable() {
#Override
public void run() {
// use the String someStr directly
System.out.println(someStr);
}
}).start();
You can use the constant which is declared in the code where the anonymous class is defined. If you'd use a private inner class you'd have to give these constants to the constructor of the class in order to use them!
You can always avoid using of anonymous classes by defining new class implicitly. However in some cases it's better to use anonymous classes. Consider following example:
void main() {
new Thread(new Runnable(){
public void run() {
System.out.println("Hello world");
}
}).start();
}
Code snippet above is more readable and shorter then defining new class.
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Hello world");
}
}
void main() {
new Thread(new MyRunnable()).start();
}
In Java 8 labmda can be used instead of anonymous class in some cases
Runnable task = () -> { System.out.println("hello world"); };
new Thread(task).start();
Are there any cases when it is unavoidable to use anonymous classes...
No. You could always define a named class for that. The point of annonymous classes is to make the code more concise and compact in situations in which you only need to use a class once.
it is advised to use them instead of named classes?
It depends on the context of the class being created.
if you are implementing interfaces having only one function (i.e Runnable) then using lambda expression instead of anonymous classes is not a bad choice.
lamba expression
I was reading through one of Oracle's lambda expression tutorials, and came across the following code:
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html
public class RunnableTest {
public static void main(String[] args) {
System.out.println("=== RunnableTest ===");
// Anonymous Runnable
Runnable r1 = new Runnable(){
#Override
public void run(){
System.out.println("Hello world one!");
}
};
// Lambda Runnable
Runnable r2 = () -> System.out.println("Hello world two!");
// Run em!
r1.run();
r2.run();
}
}
My question is why didn't they implement Runnable when creating the class? Since they overrode the run method when initializing r1, did that take care of the implementation?
Yes, this is called an anonymous class in Java.
https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
You can implement an interface or extend a class when using the new operator, which will create a new instance of the unnamed subclass you define at the time. It's mostly used when you're writing code to be used in another thread or as a callback, since you only get the one instance.
The new lambda syntax in Java 8 replaces anonymous classes for interfaces with a single method, such as Runnable or the interfaces in java.util.function. This is what they're demonstrating in the example.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Example ex = new Example();
ex.setVisible(true);
}
});
Here a block of code follows new Runnable(). How do I understand this code? I don't remember we can pass a code block directly to any object in java.
It is not a code block. It is an object.
When you say,
new Runnable()
you are creating an object that implements the Runnable interface, specifically the run() method.
As the method name suggests, invokeLater() will invoke the run() method of your runnable interface implementation object (or Runnable object) at some later point in time.
As another poster mentioned, this is an example of Anonymous Classes. It is really a convenience mechanism to quickly write code in a more concise fashion. If you don't like this, you can do it this way -
Create a new class that implements Runnable -
public class RunnableImplementation implements Runnable
{
public void run()
{
Example ex = new Example();
ex.setVisible(true);
}
}
Then, the code in your example becomes -
SwingUtilities.invokeLater(new RunnableImplementation());
It's creating an instance of an anonymous inner class. Rather than deriving a named class from Runnable and creating an instance of it, you can do the whole thing inline.
See Anonymous Classes.
You are not passing any code block, you are actually overriding the run method of the Runnable class
How do understand this code? This is such called swing event queue which helps to prevent concurrency problems. It invokes method run() on each Runnable object in this queue in sequential order.
Your code
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Example ex = new Example();
ex.setVisible(true);
}
});
is equivalent to
SwingUtilities.invokeLater(new MyRunnable() );
where MyRunnable is a class that implements the Runnable interface with the code you have and is created only for this purpose and cannot be used again.
Note MyRunnable is not the actual name, just made it up to show the point.
I'm currently taking a course in Java and I've run into some confusing code.
Example:
Runnable runnable = new Runnable()
{
public void run()
{
//doStuff
}
};
I don't really get what this code is doing.
How can the run method be associated with an instance of a class?
I googled "Runnable" and found out that it is an interface. Am I implementing the interface by declaring the run method between curly brackets ? Can this be done for any interface in java ?
I could use some links/explanations. Thank you!
It's an anonymous inner class that's implementing the interface Runnable. Yes, you can implement any interface this way, although there are reasons why you would or wouldn't in any given case (lack of reusability being a big one in the "wouldn't" column). More about anonymous classes here, but it's basically a convenient form of this:
// Define it
class Foo implements Runnable
{
public void run()
{
// Do stuff
}
}
// And then use it
Runnable runnable = new Foo();
...provided Foo is an inner (or "nested") class. More about nested classes here.
yes, you are implementing the interface by declaring the run. Yes it can be done for any interface.
This is typically done when you pass an implementation to a method that expects an argument of an Interface type, and you don't have a declared class that is appropriate. You can just implement the interface on the spot, and that code runs. Pretty neat.
I googled "Runnable" and found out
that it is an interface. Am I
implementing the interface by
declaring the run method between curly
brackets ? Can this be done for any
interface in java ?
Yes!
This code is instantiating an object which implements Runnable. Because we can't actually construct an interface, any code which attempts to do so must provide implementations for the interface's methods in curly brackets. We don't really get to see what class Java is creating to implement Runnable (these are abstract terms).
If you were to do the following:
Runnable runnable = new Runnable()
{
public void run()
{
System.out.println("I'm running");
}
};
runnable.run();
you would see "I'm running" as your output.
In some situation , this sample code will be useful .... test runna = new test()
class test implements Runnable{
test(){
Thread t = new Thread(this);
t.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("asd");
}
}
}