Solved

java nested method definition

Posted on 2013-05-29
7
318 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
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 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.
Suggested Courses

636 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