Solved

java nested method definition

Posted on 2013-05-29
7
312 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Starting to learn JAVA, 7 58
java  and programming certification ? 4 86
Strange loading of website behaviour 3 31
micro services spring boot application error 3 136
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
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.

948 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

21 Experts available now in Live!

Get 1:1 Help Now