Tutorial Q&E : Implementing Nested Classes, Question 2

//1.3
Taken from http://java.sun.com/docs/books/tutorial/java/javaOO/QandE/nested-answers.html
import java.util.*;
public class Problem {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
System.out.println("Exiting.");
timer.cancel();
5000);
System.out.println("In 5 seconds this application will exit. ");
Question 2: The program Problem.java (above) doesn't compile. What do you need to do to make it compile? Why?
Answer 2: Add final in front of the declaration of the timer variable. A nested class declared within a method has access to any final, local variables in scope.
Could somebody please elaborate on this answer for me? I don't really feel it gives enough information for me to understand fully the "why?" part.
Thanks
Mark

Hi,
the problem is that the instace of the nested class is still existing after the execution of the method has been finished. But how should it have access to a variable which doesn't exists anymore?
The only way to solve this problem is to declare the variable as final. Because then the value of the variable is known when the instance of the nested class is created an can be copied. Then at each place in the nested class where the variable is used, the copy is used instead. This is only valid because the value of the variable cannot be changed after the creation of the nested class' instance.
Andre

Similar Messages

  • Questions concerning Nested Classes

    Hi!
    Just read some articles about nested classes (include the ones from the Java Tutorial and the Effective Java chapter), and while most of it is perfectly clear, three questions remain:
    1.) When I declare a member class, how should I declare the access specifiers (private, protected etc.) for the member class's attributes and methods? If I declare a member class as private, anything but private for the attributes and methods wouldn't make sense, would it?
    2.) The Java Tutorial says:
    Also, because an inner class is associated with an instance, it cannot define any static members itself.While this is true for static methods, it seems to be possible to declare static variables inside inner classes. This is confusing me... does it actually make sense to declare static variables inside inner classes (or member classes in general)? Or should the be placed in the declaring class?
    3.) Another confusing quote from the Java Tutorial:
    Static nested classes do not have access to other members of the enclosing class.This is true for instance variables and methods but not for static variables, which are also members of the enclosing class, aren't they?
    Thanks in advance,
    OIiver

    Trollhorn wrote:
    Hi!
    Just read some articles about nested classes (include the ones from the Java Tutorial and the Effective Java chapter), and while most of it is perfectly clear, three questions remain:
    1.) When I declare a member class, how should I declare the access specifiers (private, protected etc.) for the member class's attributes and methods? If I declare a member class as private, anything but private for the attributes and methods wouldn't make sense, would it?
        private static class MyInner implements Runnable
            @Override public void run() // Must be public!
    2.) The Java Tutorial says:
    Also, because an inner class is associated with an instance, it cannot define any static members itself.While this is true for static methods, it seems to be possible to declare static variables inside inner classes. This is confusing me... does it actually make sense to declare static variables inside inner classes (or member classes in general)? Or should the be placed in the declaring class?Wrong. It can define static final member variables and I see no reason to move them to the outer class, if they are used only by the inner class.
    3.) Another confusing quote from the Java Tutorial:
    Static nested classes do not have access to other members of the enclosing class.This is true for instance variables and methods but not for static variables, which are also members of the enclosing class, aren't they?I agree with you here.
    Edited by: baftos on Jun 6, 2009 9:18 AM

  • JDWP reference implementation does not return anonymous nested classes?

    Using
    $ java -version
    java version "1.6.0_22"
    Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
    Java HotSpot(TM) Client VM (build 17.1-b03, mixed mode, sharing)
    it appears that when I connect with JDWP and issue a NestedTypes command, the result does not include anonymous nested types. The only references to this that I could find is a comment in a svn commit at apache (http://mail-archives.apache.org/mod_mbox/harmony-commits/200611.mbox/%[email protected]%3E)
    Is this intentional and desired? Is there a way to get all of the nested types, including the anonymous ones? I could do ClassesBySignature with "package.ClassName$*" as the signature and filter out doubly nested classes, but that seems overly complicated.

    exept, you can NOT have an implementation of an
    abstract class (which foundPlugin) is without an
    implementation of all it's subclasses (such as
    argsObject) You're mistaken in a couple of ways here.
    First, a nested class is not the same as a subclass.
    Second, a concrete class must have implementations for all its methods, but it can still have an abstract nested class.
    Third, you can have an instance of a concrete class that has abstract subclasses. Object is concrete and has many concrete subclasses. Classes don't know anything about their subclasses.
    This compiles.
    public abstract class AbOut {
      public abstract class AbIn {  public abstract void bar(); }
    public class ConcOut extends AbOut {
      public abstract class AbIn2 { public abstract void foo();}
    foundPlugin MUST have an implementation
    of argsObject, according to the rules of java,And you think this because...?
    You read it in the JLS? Citation please.
    You tried to compile and it failed? My sample above demonstrates the countereample. If I'm misunderstanding what you're talking about, please post an example
    Or maybe you just thought it had to be that way because that seemed the most intuitive and when it wasn't, rather than trying to understand or adjust your thinking, you figured it would be more fun to throw a hissy fit and call Java "stupid"?

  • Question about nested classes

    Hi, i currently have the following problem:
    I have 2 classes, one of which also has a nested class:
    1. Home.java (extends JApplet)
    2. Away.java (extends JPanel) has nested class, private class ButtonListener implements ActionListener
    Now in Home.java I have a Vector ( called bankaccount) which i pass to the Constructor of Away.java ( I declared the vector again there as an instance by Private Vector bankaccount;).
    My problem is that in ButtonListener I am trying to access the Vector so that i can modify it when a button has been clicked, and i thought i could just use the commands of bankaccount.add() and bankaccount.get() directly, however it seems like ButtonListener cannot access the Vector, even though i passed it along to the Constructor of the Away class.
    Any suggestions on how i get access the Vector from the ButtonListenere class?

    This is an example:
    public class Home extends JApplet
    private Away away;
    private Vector bankaccount;
    public void init()
         bankaccount = new Vector();
         away = new Away(bankaccount);
    public class Away extends JPanel
    private Vector bankaccount;
    JTextArea text1= new JTextArea(50,50);
    public Away(Vector bankaccount)
       //declare buttons,textarea,setLayout,etc
    button1.addActionListener (new ButtonListener());
    //i can set  text1.setText(( String)bankaccount.get(0));
    // here to access bankaccount, and it shows up fine, but i want
    // do it in from the class below
    private class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event)
                         //trying to access bankaccount here by doing:
                        // but it is not doing anything
                        text1.setText(( String)bankaccount.get(0));
    }

  • Question about the property of the nested class.

    "Nested classes may be declared static. In this case, the nested class has no reference to an enclosing instance"
    Can any one demonstrate the above through an code example?? thanks

    thanks jverd.
    Then why dont you answer my other thread??You have several threads. I've said what I have tosay in all the ones that I know about, am interested
    in, and have the time to answer. Last one I lookedat, you were in Monica's very capable hands, so I had
    nothing to add.
    Thanks!I may not be the sharpest knife in the drawer, but I know better than to piss of her what's gonna administer the dread Blueberry Pie Torture.

  • Inner Class Question

    My question pertains to the code at the bottom of this post.
    I don't understand why the compiler doesn't give an error for the line below. Why would it let you refer to something inside the class (in this case I'm referring to ClassWithInnerClass.MyInnerClass) unless it were static?
    ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();To illustrate why I'm asking, I created 2 ints ("regularInt" and "staticInt") inside class "ClassWithInnerClass". The compiler let me set the value of "staticInt" from within main whereas it wouldn't let me do so w/ "regularInt" (which is why I commented that line out). Don't get me wrong though - I understand the reasons why the compiler behaves as it does for "regularInt" and "staticInt". I understand that a static variable can be accessed without instantiating a class (and that there's only 1 created no matter how many classes are instantiated). I also understand that, to access a non-static variable, you need to instantiate a class. My question arises only because of trying to extend that logic to MyInnerClass.
    I can already take a guess that the answer is going to be something like, "the reason it works this way is because class 'MyInnerClass' is just a declaration NOT a definiton". I guess I just want confirmation of this and, if possible, some reasoning behind this logic.
    HERE'S THE CODE...
    class CreateInnerClasses {
         public static void main (String args[]) {
              ClassWithInnerClass cwic = new ClassWithInnerClass();
              ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();
              //ClassWithInnerClass.regularInt = 5;
              ClassWithInnerClass.staticInt = 10;
              mic.printIt();
    class ClassWithInnerClass {
         public int regularInt ;
         static public int staticInt;
         class MyInnerClass {
              void printIt() {
                   System.out.println("Inside ClassWithInnerClass.myInnerClass");
         MyInnerClass retMyInnerClass () {
              return new MyInnerClass();

    The line    ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();is accepted because the name of the inner class is ClassWithInnerClass.MyInnerClass. This has nothing to do with accessing fields even though the syntax is similar.
    On the other hand, the line    SomeClassWithAnInnerClass.InnerClass ic = new SomeClassWithAnInnerClass.InnerClass();is not accepted because the nested class SomeClassWithAnInnerClass.InnerClass is not static: you must have an instance of the outer class available. The correct syntax for calling the constructor of the inner class would be    Outer.Inner instance = outerInstance.new Inner();In this case you could write:    ClassWithInnerClass.MyInnerClass mic =  new SomeClassWithAnInnerClass() . new InnerClass();
        // OR:
        ClassWithInnerClass.MyInnerClass mic =  cwic . new InnerClass();The Java tutorial has a pretty good explanation on nested classes:
    http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
    http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html

  • Flex RPC mapping Java nested classes to ActionScript classes

    We are calling a Java method in our project using
    RemoteObject the value returned by the java method is a ArrayList
    containing instances of a class say ParentClass with some nested
    classes.
    The structure of ParentClass(Java) is something like this
    class ParentClass {
    //some primitives
    private ChildClassA childAInstance;
    private ChildClassB childBInstance;
    //getters setters
    We have created similar class structure on the ActionScript
    side, the ActionScript classes(ParentClass,ChildClassA
    ,ChildClassB) have been properly annotated with the [RemoteClass]
    metadata tag,
    The problem is that though i'm getting the primitive data
    members of the ParentClass through RPC in my corresponding AS
    ParentClass class i'm getting an runtime exception trying to access
    ChildClassA,ChildClassB members.
    Am i missing something, exactly the same scenario is
    mentioned in this article
    http://www.adobe.com/devnet/flex/articles/complex_data.html
    But the Object.registerClass method mentioned in the tutorial
    is giving me compilation error, the sample code attached with the
    article is corrupt zip too.
    Please help me out on this

    JAXB will create classes from an XML schema, SAX is a parser library and JAXP is a library of XML a bunch of XML tools.
    I don't care for JAXB too much. I would skip it and go right to the JAX-RPC spec (WebServices).

  • Nested Classes in Labview 8.2

    hello everyone,
    I am a 'measurement studio' convert to labview, so I have been getting my head around the 'object oriented programming' features of labview 8.2. There seems to be many things lacking in this implementation, like Java/C# style interfaces, and abstract classes.
    Also I haven't found a way to create a nested class (so a class within a class). Is this possible in Labview 8.2 or 8.5?
    Thanks,
    paul

    I just stumbled across this post looking for other information......
    Is it true that nested classes are not supported?
    I just tried this out and it seemed to work for me.  Can we add a class as a data member of another class?  I think I recall this even being propagated in an article, but I can't remember which.
    I think it was about an object referencing itself in it's own data field to create a recursive object call.....
    Can someone please confirm that nested classes are supported and working?  Which caveats need to be observed?  I'm just starting working on something which kind of relies on the ability to nest classes, so I'm quite interested as to whether it's feasible or not.
    I'm using LV 8.2.1.
    Shane.
    Using LV 6.1 and 8.2.1 on W2k (SP4) and WXP (SP2)

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this...
    [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
    I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • How to ensure multiple nested classes static readonly initialization orders

    Hello,
    I am emulating the Java Enumeration in a first class class, with static readonly field initialization.
    In an effort to further categorize some instances, I embed them in nested classes. Something like this.
    class A : Enumeration
    public static class CatB
    public static readonly A FirstInstance = new B();
    public static readonly A SecondInstance = new B();
    public static class CatC
    public static readonly A ThirdInstance = new C();
    public static readonly A FourthInstance = new C();
    class B : A
    class C : A
    So far so good.
    One strain of Enumeration has built-in Ordinals, so I initialize them in the static ctor, or I make an effort to.
    static A()
    var values = GetValues().ToList();
    var ordinal = 0;
    values.ForEach(v => v.Ordinal = ++ordinal);
    Also, in places, so far so good.
    However, in a main method, I am referencing one of the enumerated instances, so calls to my GetValues() is returning nulls for that nested class. The other nested class instances are just fine, they return just fine.
    I could post more, but I think this illustrates the idea.
    I am suspicious that a strange static initialization order is jumbled up, as evidenced by nested static ctor debug statements I put in. I get one print and not the other.
    When I switch up which instance I reference in my main, I get the opposite behavior, more or less confirming my suspicions.
    So... Question is, what's the best way to potentially work around this issue? Hopefully without abandoning the Enumeration concern altogether, but that thought is a possibility as well. Or at least do so differently.
    Thank you...

    It is probably necessary to show GetValues() at least. I am getting the correct nested types, so that much we can at least assume.
    protected static IEnumerable<TDerived> GetValues()
    var declaringTypes = GetDeclaringTypes(typeof (TDerived)).ToArray();
    foreach (var declaringType in declaringTypes.Reverse())
    var fis = declaringType.GetFields(PublicStaticDeclaredOnly);
    var values = fis.Select(fi => fi.GetValue(null)).ToArray();
    foreach (var value in values.OfType<TDerived>())
    yield return value;
    Okay, here a bit of explanation.
    Enumeration is declared generically, with TDerived as the derived type. In this case, A.
    GetDeclaringTypes is operating okay. I get types for A, B, and C.
    The fis to values is breaking down, however. When I reference any of the CatB's, I get nulls for those instances. Conversely, same for CatC's when I reference any of those.

  • ActionListener as nested class, anonymous class etc.

    I'm programing my own text editor and im trying to decide in what way to implement an ActionListener for JMenuItems.
    I've got 3 possible ideas of how to implement it.
    First way is to implement the ActionListener in the same class as the JMenu and use a switch statement or a fairly long if-else statement.
    Second way is to create nested classes for each ActoinEvent.
    public class OuterClass {
         //Some random code here...
         private class ActionClass implements ActionListener{
              public void actionPerformed(ActionEvent e) {
                   //Random code.
    }And final way is creating anonymous classes adding ActionListeners for each JMenuItem.
    menuItem.addActionListener(new AbstractAction(){
    public void actionPerformed(ActionEvent e) {
    });But i can't decide on wich of these are the moste correct and accepted way.
    Could someone point me to the right direction?
    Edited by: Idono on Jun 3, 2010 7:36 PM

    the only time you would do the first one would be if you wanted several ActionListeners to do the EXACT SAME THING.
    Then you just write the "actionClass" one time, and have each Component use it.
    private class ActionClass implements ActionListener{
              public void actionPerformed(ActionEvent e) {
                   //Random code.
    menuItem.addActionListener(new ActionClass());
    menuItem1.addActionListener(new ActionClass());
    menuItem2.addActionListener(new ActionClass());
    menuItem3.addActionListener(new ActionClass());But (as the other person mentioned) usually you use anonymous classes because each component has different actions.
    menuItem.addActionListener(new AbstractAction(){
    public void actionPerformed(ActionEvent e) { ... }
    menuItem1.addActionListener(new AbstractAction(){
    public void actionPerformed(ActionEvent e) { ... }
    menuItem2.addActionListener(new AbstractAction(){
    public void actionPerformed(ActionEvent e) { ... }
    });

  • Are static nested classes thread-safe?

    There doesn't seem to be any definitive answer to this. Given the following code, is it thread-safe?
    public class SomeMultiThreadedWebController {
    public HttpServletResponse someMethodToExecuteViaWebRequest(HttpServletRequest request) {
        simpleQueryBuilder("SELECT...").addParameter("asdf","asdf").createQuery(EMF.getEntityManager()).executeUpdate();
    protected static class SimpleQueryBuilder {
             private String queryString;
             private Map<String, Object> params = new HashMap<String, Object>();
             public SimpleQueryBuilder(String queryString) {
                  this.queryString = queryString;
             public SimpleQueryBuilder addParameter(String name, Object value) {
                  params.put(name, value);
                  return this;
             public Query createQuery(EntityManager em) {
                  Query query = em.createQuery(queryString);
                  for (Entry<String, Object> entry : params.entrySet()) {
                       query.setParameter(entry.getKey(), entry.getValue());
                  return query;
        public static SimpleQueryBuilder simpleQueryBuilder(String queryString) {
             return new SimpleQueryBuilder(queryString);
    }Forget whether or not someone would do this, as this is just an example. I'm really trying to get at whether or not the instance variables inside the static nested class are thread-safe. Thanks for any responses.

    Hello,
    I believe you understand what you're talking about, but you state it in a way that is very confusing for others.
    Let me correct this (essentially, incorrect uses of the terminology):
    I agree that thread-safe or not is for an operation, for a member, it has some sort of contextual confusion.
    Member has a much broader meaning in the [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4] . Even "class member" applies to both an attribute, a method, or an inner class or interface.
    I think you mean "member variable" of a class (aka "attribute" or "field"). By the way, static or not is irrelevant to the rest of the discussion.
    For an operation or a member, if there's only one thread could access it atomically in one moment, we could call it thread-safe.Mmm. I was tempted to say yes (I'm reluctant to commit myself). With an emphasis on "_The encapsulating class_ makes this member's usage thread-safe".
    Still, just synchronizing each operation on a member is not enough to make all usages "thread-safe":
    Consider a java.util.Vector: each add/get is synchronized, so it is atomic, fine.
    However if one thread adds several values, let's say 3, one by one, to a vector that initially contains 0 values, and another thread reads the vector's size() (another properly synchronized method), the reader thread may witness a size anywhere among 0, 1, 2, 3, which, depending on the business logic, may be a severely inconsistent state.
    The client code would have to make extra work (e.g. synchronizing on the vector's reference before the 3 adds) to guarantee that the usage is thread-safe.
    Thus any synchronized method(With the limit stated above)
    or immutable member (like primitive type) are thread-safe.
    Additionally for a member, if it's immutable, then it's thread-safe. You mean, immutable primitive type, or immutable object. As stated previously, an immutable reference to a mutable object isn't thread-safe.
    a static final HashMap still have thread-safe issue in practice because it's not a primitive.The underlined part is incorrect. A primitive may have thread-safety issues (unless it's immutable), and an object may not have such issues, depending on a number of factors.
    The put, get methods, which will be invoked probably, are not thread-safe although the reference to map is.Yes. And even if the put/get methods were synchronized, the client code could see consistency issues in a concurrent scenario, as demonstrated above.
    Additional considerations:
    1) read/write of primitive types are not necessarily atomic: section [ §17.7 of the JLS|http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7] explicitly states that writing a long or double value (2 32-bits words) may not be atomic, and may be subject to consistency issues in a concurrent scenario.
    2) The Java Memory Model explicitly allows non-synchronized operations on non-volatile fields to be implemented in a "thread-unsafe" way by the JVM. Leading way to a lot of unintuitive problems such as the "Double-Checked Locking idiom is broken". Don't make clever guess on code execution path unless you properly synchronize access to variables across threads.
    Edited by: jduprez on Mar 4, 2010 9:53 AM

  • JIT compiler and nested classes

    Q1. how does JIT compile on fly and improve the performance ?
    Q2. how is system.out.println(argument) implemented in java ? is it that system is a class in which out is a static nested class and println is a static method in out?

    Hello rishiluvsjava,
    Q1. How does JIT compile on fly and improve the performance?
    The following answer was taken from "The Java HotSpot Performance Engine Architecure: A White Paper About Sun's Second Generation Performance Technology" to view the full document go to:
    http://java.sun.com/products/hotspot/whitepaper.html
    Just-In-Time (JIT) compilers are essentially fast traditional compilers that translate the Java-technology bytecodes into native machine code on-the-fly. A JIT runs on the end-user's machine which actually executes the bytecodes, and compiles each method the first time it is executed.
    Q2. How is System.out.println(argument) implemented in java ? is it that system is a class in which out is a static nested class and println is a static method in out?
    From the Java docs:
    System is a public final class in the java.lang package. It has three fields:
    static PrintStream err    // The "standard" error output stream.
    static InputStream in    // The "standard" input stream.
    static PrintStream out  //The "standard" output stream.println is one of the methods in the java.io.PrintStream class.
    -Merwyn,
    Developer Technical Support,
    http://www.sun.com/developers/support.

  • Bytecode class names (nested classes)

    Hi,
    with my JVMTI agent on a 1.5 JVM I found class names like this:
    Lsun.misc.URLClassPath$JarLoader
    Ljava.util.HashMap$Entry
    which show nested classes inside of other classes. The point is, that those nested classes (behind '$') here have a name.
    But what about those:
    Lsun.misc.Launcher$AppClassLoader$1
    Ljava.util.zip.ZipFile$2
    Ljava.lang.Class$1
    Ljava.lang.ref.ReferenceQueue$Null
    They dont have a name? How is this possible? Is it inline creation of an abstract class for example which results in unnamed (and then numbered) nested classes? And what about that "Null" ?
    Robert

    Cross-posted.
    http://forum.java.sun.com/thread.jspa?threadID=738470
    Robert: do not ask your question repeatedly in different areas. At the very least post a link to your question in other areas. Otherwise you waste peoples time, if the question has already been answered somewhere else.

  • Nameless Nested Classes passed in Function Parameter?

    I am trying to get my head around the following code example:
    javax.swing.SwingUtilities.invokeLater( new Runnable() { public void run() { createAndShowGUI(); }});What is actually getting passed to the SwingUtilities.invokeLater() function?
    Can anyone explain all of the parts and pieces of :
    new Runnable() { public void run() { createAndShowGUI(); }} ?
    Here is my best guess:
    1) { public void run() { createAndShowGUI(); }} is an unnamed nested class that is instantiated using the Runnable() interface.
    2) this class has one method called run() that executes createAndShowGUI();
    Is my best guess even close to what is really going on?

    richard.broersma wrote:
    1) { public void run() { createAndShowGUI(); }} is an unnamed nested class that is instantiated using the Runnable() interface.Yes, that's essentially correct. It's called an anonymous inner class.
    This is similar to doing
    // a non-anonymous inner class
    private class MyClass implements Runnable
      public void run()
        createAndShowGUI();
    MyClass myclass = new MyClass();
    javax.swing.SwingUtilities.invokeLater(myclass);
    2) this class has one method called run() that executes createAndShowGUI();Yes. It must have a parameterless public void run method since it implements the Runnable interface.
    Is my best guess even close to what is really going on?Yes, you're catching on.

Maybe you are looking for