Solved

java nested method definition

Posted on 2013-05-29
7
309 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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
mapBully challenge 6 92
What is JNDI datasource in spring 1 38
Java Jpanels and Jframe 8 20
Java Server Faces parameter pass? 6 24
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
This video teaches viewers about errors in exception handling.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

760 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now