Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a block of code do after a new operation in Java?

Tags:

java

swing

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.

like image 898
OneZero Avatar asked Apr 29 '13 19:04

OneZero


People also ask

How is a block of code created what does it do in Java?

Introduction: code block in Java A code block is a section of code enclosed in curly braces {} . Code blocks are used to group one or more statements. Code blocks can be nested, meaning you can have code blocks inside of other code blocks. The code block in the code above contains a single statement, int x = 10; .

How do you initialize a new object in Java?

Creating an Object Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

Why do we initialize objects in Java?

Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable. We can also create multiple objects and store information in it through reference variable.


2 Answers

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()); 
like image 199
CodeBlue Avatar answered Oct 18 '22 15:10

CodeBlue


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.

like image 26
RichieHindle Avatar answered Oct 18 '22 14:10

RichieHindle