Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

java nested method definition

Posted on 2013-05-29
7
Medium Priority
?
321 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 668 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 664 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

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 36

Accepted Solution

by:
mccarl earned 668 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses

916 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