Solved

java nested method definition

Posted on 2013-05-29
7
314 Views
Last Modified: 2013-05-30
Hello all,

Can someone explain what is going on in the following code or explain an alternative syntax? it looks like a method is being defined (run()) within another method call (invokeLater())..in particular, the syntax new Runnable() { is a little confusing..That is, i have seen nested constructors before such as:

ObjectInputStream o = new ObjectInputStream(new FileInputStream("inputfile.txt"));

Open in new window


But i havent seen a method call like the following:

public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

Open in new window


thanks
0
Comment
Question by:oggiemc
7 Comments
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 167 total points
ID: 39204116
That (which looks like i might have written it ;)) is passing an anonymous instance of Runnable to invokeLater such as to ensure that the gui be created on the Swing event dispatch thread:

http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable)
0
 
LVL 26

Assisted Solution

by:ksivananth
ksivananth earned 166 total points
ID: 39204120
>>ObjectInputStream o = new ObjectInputStream(new FileInputStream("inputfile.txt"));

its the simple form of below,

FileInputStream fis = new FileInputStream("inputfile.txt") ;
ObjectInputStream o = new ObjectInputStream( fis ) ;

>>public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
>>

this is called anonymous inner class. SwingUtilities.invokeLater expects an instance of Runnable interface. the anonymous implementation of Runnable is represented as

new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        }
0
 

Author Comment

by:oggiemc
ID: 39204499
Thanks for replies guys,

ksivananth,

Thanks for pointing out the name of this construct (anonymous inner class)...Could you please show me an alternative syntax to this? I was looking for an alternative syntax to the anonymous inner class, not the ObjectInputStream..

Thanks
0
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 

Author Comment

by:oggiemc
ID: 39204597
Another question i have here is, where is the run method actually called in the code below??

import javax.swing.*;
// Importing the package that contains all the Swing Components and Classes.
    
public class FrameExample {
    
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    
    private static void createAndShowGUI() {
        //Create and set up the frame. 
        //The string passed as an argument will be displayed 
        //as the title.
    
        JFrame frame = new JFrame("[=] Hello World [=]");
    
        //Display the window.
        frame.setSize(400, 100);
        frame.setVisible(true);
    }  
}

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39205135
The run method is a callback method, called by SwingUtillities.invokeLater, which is the one and only statement in main
0
 
LVL 35

Accepted Solution

by:
mccarl earned 167 total points
ID: 39206769
Ok, so the basic alternative to the code that you posted (which you now know as an 'anonymous inner class'), is a "named inner class" or just "inner class" or "nested class". The main difference with this is that since the class has a name, you can refer to it by name, and you can also refer to it multiple times (if needed). Also, since it is defined in the scope of the class that contains it, you can refer to it anywhere within that class (also if you mark it as public you can refer to it from outside the class too, but i digress). Here's the code, note I have also included the containing class (OuterClass) and the createAndShowGUI() method skeleton, just for completeness...
public class OuterClass {
    private static void createAndShowGUI() {
        // Do your GUI stuff here...
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new MyRunnable());
    }

    private static class MyRunnable implements Runnable {
        public void run() {
            createAndShowGUI();
        }
    }
}

Open in new window

0
 

Author Comment

by:oggiemc
ID: 39207163
Hi mccarl..Thanks, that has really cleared it up..The anonymous inner classe is a strange syntax when you first come accross it but it makes sense now..
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question