A question about local inner classes

Suppose an inner class created in a method:
public void thisMethod(final int a){
             class InnerClass {
               //code
}Why, in order to use the parameter a in the inner class, I have to pass it final?

Aurelious wrote:
JoachimSauer wrote:
Because you can't refer to the argument of a method once the method call is completed (since the method argument lives on the stack).Why does that matter? If the parameter is of a primitive type, the object will get a copy of it anyway. If the parameter is not primitive, then the value on the stack will be a reference to the argument and not the argument-object itself. In either case, it should then be safe to modify the value after the method returns, as it will either be the primitive copy or a copy of a reference to the object which is itself not on the stack, so the field referenced by the object is still valid either way.
Am I missing something?If your inner class is using a local variable in the calling method, the expectation is that it's the same variable. But it's not. If it were, then when the stack frame was popped, the variable would be out of scope, which is incompatible with the fact that the inner object can live on.
On the other hand, if we copy it without making it final, then that's misleading. It looks like I have the same variable, but if I change it in the method, it doesn't change in the object, and vice versa.
So we have to make a copy to prevent scope/lifetime problems, and we have to make it final so that the copy can be indistinguishable from it being the same variable.

Similar Messages

  • Question about anonymous inner class??

    Is there any error occurs,If a class declear & implement two anonymous inner classes ??

    public class TryItAndSee {
        void m() {
            Runnable x = new Runnable(){
                public void run() {
                    System.out.println("?");
            Runnable y = new Runnable(){
                public void run() {
                    System.out.println("!");
    }

  • Why method local inner class can use final variable rather than....

    Hi all
    Just a quick question.
    Why method-local inner class can access final variable defined in method only?
    I know the reason why it can not access instance variable in method.
    Just can not figure out why??
    any reply would be appreciated.
    Steven

    Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren't final then the copy of the variable in the method could change, while the copy in the local class didn't, so they'd be out of synch.

  • Local inner classes

    Hi all,
    Local inner classes can access all instance / static variables (include private) from enclosing class & local variables / methods parameters declared as final.
    class Outer {
    private int a = 0;
    static int b = 1;
    public void localInnerClassTest(final int k) {
    final double x = 0.4;
    class LocalInner {
    public void test() {
    System.out.println(a + " " + b + " " + k + " " + x);
    new LocalInner().test();
    public static void main(String args[]) {
    new Outer().localInnerClassTest(3);
    // shows 0 1 3 0.4
    I�ve seen in some mock exams that�s wrong ...
    Thankz

    Local inner classes can access all instance / static
    variables (include private) from enclosing class &
    local variables / methods parameters declared as
    final.Yes. That is correct
    >
    I�ve seen in some mock exams that�s wrong ...You've seen that what's wrong? - the statement you made above or the code you posted?
    The code you posted should not compile (is that what you mean by "wrong"), but you have not explained the problem you are having...
    Do you have a question you would like answered?

  • Question about required workshop classes for OCP

    Im working on finishing up my OCP in a few months. Quick question about the workshop class. Is there a test at the end of the week?
    Also how do most people pay for these classes? They are pretty steep and my company doesnt pay for stuff like this for me. Im paying totally out of my own pocket. Also why is the online class the same amount as the instructor lead class? Its not like im in a room at some building that Oracle has to lease for use or something.

    RedDeuce wrote:
    Im working on finishing up my OCP in a few months.What Certificate exactly are you working towards?
    Also how do most people pay for these classes? They are pretty steep and my company doesnt pay for stuff like this for me. Im paying totally out of my own pocket.Then talk to your employer again or maybe look for other jobs that support your plan better.
    Also why is the online class the same amount as the instructor lead class? Its not like im in a room at some building that Oracle has to lease for use or something.They know that you might save on expenses for travel and hotel etc.

  • Inaccessible with local variable(non-final) via method local inner class

    Hi All,
    Usually local variables, including automatic final variable live on the stack and objects & instanace variables live on the heap.The contracts for using the method local inner class should allow merely method final variable, not non-final stack variable.
    Can anyone please clarify me ,behind the scene what is actual fact why method inner class should not access the stack(method) variable and only allow final variable?
    Is anything correlated with the stack and heap aspects?
    Thanks,
    Stalin.G

    [email protected] wrote:
    ...behind the scene what is actual fact why method inner class should not access the stack(method) variable and only allow final variable?...explained by dcminter and Jardium in [an older thread|http://forums.sun.com/thread.jspa?messageID=10694240#10694240|http://forums.sun.com/thread.jspa?messageID=10694240#10694240]:
    ...Final variables are copied into inner classes - that's why they have to be declared final; to avoid the developer making an incorrect assumption that the local variable can be modified and have the change reflected in the copy.
    When a local class uses a local variable, it doesn't actually use the variable. Instead, it takes a copy of the value which is contained in the variable at the moment the class is instantiated. It's like passing the variable to a constructor of the class, except that you do not actually declare any such constructor in your code.
    To avoid messy execution flows to be present in a Java method, the Java language authors thought it was better to allow a single value to be present in such a variable throughout all its life. Thus, the variable has to be declared final.
    ...HTH

  • Question about Local Variables (Multiple answers welcomed!)

    A couple of questions about Local Variables
    1. Programmers always say: “Do not abuse of Local Variables”. I’d like to know, when and where Local variable are most efficiently used?
    2. If I have to create a couple of local variables, is there anyway to “clone” them without going through the repetitive “create/local variables” mouse click each time? (When I try to copy and paste, it creates a new variables instead of the one that I am trying to reproduce)
    3. Which is faster in execution: Updating a variable through a) writing to property node/value or b) through local variable
    Everyone’s input is welcomed, so if this question is already answered, please
    feel free to add additional comments/answers!

    1. Use Local Variables in user interface code and no where else. The only exception is using a local variable of a cluster output to define the datatype for a bundle by name node.
    2. You can drag copy them then right click to get to a menu of all the currently defined controls and indicators on the VI.
    3. B. The problem with A is that it forces a thread switch to the user interface thread--which can take time if you aren't already in it, and it's a very convoluted process under the hood. NI's advice never update indicator values through a property node unless you absolutely, positively can't figure out some other way of doing it.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Method local Inner classes

    The local variables of the method live on the stack, and exist only for the lifetime of the method. You already know that the scope of a local variable is limited to the method the variable is declared in. When the method ends, the stack frame is blown away and the variable is history. But even after the method completes, the inner class object created within it might still be alive on the heap if, for example, a reference to it was passed into some other code and then stored in an instance variable. Because the local variables aren’t guaranteed to be alive as long as the method-local inner class object, the inner class object can’t use them. Unless the local variables are marked final! The following code attempts to access a local variable from within a method-local inner class.
    Can any one explaing me with an example of the above BOLDED text.

    Can any one explaing me with an example of the above BOLDED text
    class Outer {
         Outer outer;
         void method() {
              int i=0;
              class Local extends Outer {
                   int j = i;
              outer = new Local();
    }The above code doesn't compile unless the i variable in method() is declared final.

  • Less dumb follow-up question about super/sub classes in WDJ?

    This is a follow-up question to the question which Maksim answered in this thread:
    Dumb question about super/sub classes in WDJ
    Question:
    Is there any kind of weird C++-like statement that you can put at the top of a WDJ module to force the module to interpret any reference to superclass A as a reference to some specific subclass B of A ???

    David,
    1. Java has no preprocessor, so C++ tricks are not available. Also I would not recommend such tricks even in C++ if you don't want to turn your colleagues working with same code into personal enemies.
    2. The phrase "easier to create a WDJ custom class loader " makes me smile. First, it's not that simple to interfere WDJ class loading scheme. Plus custom class loaders is not trivial Java topic per se.
    3. The problem "replace all A-s with B-s" is typically solved using one or another GoF creation patterns, like <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern">Abstract Factory</a> or <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">Factory Method</a>. You may use them with custom class loader, if you really want to
    By the way, all UI controls in WD are created using Abstract Factory (role played by view). So you may use this as good example.
    Valery Silaev
    SaM Solutions
    http://www.sam-solutions.net

  • Local inner class

    *@author Rossi Kamal
    *version 1
    *easy local inner class
    public class local_inner
         final int Roll=10;
         public  void main(String args[])
              class _inner
                    int accountnumber=5;
                    int roll=Roll;
              _inner a=new _inner();
              System.out.println("Accoubtnumber"+a.accountnumber+"Roll"+a.roll);
    }

    Don't multi-post:
    http://forum.java.sun.com/thread.jspa?threadID=5130208&tstart=0

  • Few questions about Calendar / SimpleDateFormat classes

    Hi.
    I have few questions about Calendar class:
    1. How can I get only date representation (without the time)?
    after doing:
    Calendar cal = Calendar.getInstance();
    I tried to clear unecessary fields:
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.HOUR_OF_DAY);
    But after printing the time, it seems that the HOUR was not cleared:
    SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    System.out.println(sdf1.format(cal.getTime()));
    ---> 03/11/2004 17:00:00
    Am I missing somthing?
    2. I want to make sure that two different formats couldn't be compared. i.e., if I'll try to parse one String according to different format -- ParseException will be thrown.
    String date = "19/04/2004 13:06:10";
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date dateObj = sdf.parse(date);
    However, even though that formats are different, no exception is thrown and the return Date is 19/04/2004 00:00:00.
    How can I cause to exception to be thrown if formats are not identical?
    Thanks in advanced

    The Calendar class has a few of what Microsoft would call 'features'. :^)
    To clear the time, call:
    calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY), 0, 0, 0);
    If you want 'pessimistic' rather than 'optimistic' date parsing, you have two options:
    1) Call calendar.setLenient(false);
    See if that is strict enough for your needs, otherwise:
    2) Write code to ensure a stricter parsing of the string passed in. For example, you could very simply check the length of the string to determine if time data is also present.
    When parsing, a string like '02/29/02' would parse to the date '03/01/02'. Setting lenient to false may fix this, but the surest way is to do some testing and then make the parsing more pessimistic where it suits your needs.
    - Saish
    "My karma ran over your dogma." - Anon

  • Question about using container class - Map

    hi all
    i have a question about the following :
    i have two sets of data, both use a common filed as key for the map:
    A = {a,b,d,f,g,h} and B = {a,d,e,g,i,k}, each key has a value associated with.
    i need to find out the commonality, and the difference - i.e fields are in map A but not in Map B, and some fields that are in B but not in A. is there any quick method that comes with the collection class that can calculate this? thanks

    yes, the keyset will be used to access values.
    so, SetA.retainAll(SetB) will modify the SetA so that it contains keys that are in both SetA and SetB - the intersection.
    and SetA.removeAll(SetB) will modify the SetA so that it only contains keys that are in SetA, but not in SetB?
    correct?

  • Method local Inner class

    Why method local class can access only the final varaible of the method?
    I found somewhere that this is because the non-final local variables go out of scope after method completion, but i wonder final local variables also reside on the stack.
    class MyOuter2 {
    private String x = "Outer2";
    void doStuff() {
    String z = "local variable";
    class MyInner {
    public void seeOuter() {
    System.out.println("Outer x is " + x);
    System.out.println("Local variable z is " + z); // Won't Compile!
    } // close inner class method
    } // close inner class definition
    } // close outer class method doStuff()
    }

    pxNet wrote:
    and so you are now saying it accesses the original variable, not a copy of it?No, I'm not saying that at all; see reply #1. The situation is quite the opposite, the inner class accesses a copy of the variable. Direct access to the local variable is most definitely not allowed. But that doesn't have anything to do with parameter-passing semantics.
    I'll try to clarify with another demonstration of the problem. Assume that direct access to non-final local variables was actually allowed, and that the following example would compile (it won't, of course): class Outer {
        Inner method() {
            Object o = "foo";
            return new Inner() {
                public void modifyLocalVariable() {
                    o = "bar";
        interface Inner {
            void modifyLocalVariable();
        public static void main(String[] args) {
            Inner inner = new Outer().method();
            inner.modifyLocalVariable(); // what local variable is this modifying?
                                         // the local variable in method() has gone
                                         // out of scope!
    }Because of the way anonymous inner and local classes are implemented, they get a copy of the local variables (per the JLS). Mind you, there isn't any parameter passing going on at all in this example.
    ~

  • Local inner class scope

    Hello all,
    I am working out of "Thinking in Java" and ran across something I simply don't get. A method is called and passed an argument. This method defines an inner class and returns reference to it. Later a method in the inner class is invoked, but it still has access to the argument passed to the method that created the inner class and completed.
    Here is the code (shortened from the book):
    interface Counter {
         int next();
    } // close interface Counter
    public class LocalInnerClass {
         private int count = 0;
         Counter getCounter( final String name ) {
              class LocalCounter implements Counter {
                   public int next() {
                        System.out.print( name );
                        return count++;
                   } // close next()
              } // close inner class
              return new LocalCounter();
         } // close getCounter()
         public static void main( String[] args ) {
              LocalInnerClass lic = new LocalInnerClass();
              Counter c1 = lic.getCounter( "Local inner " );
              for( int i = 0; i < 5; i++ ) {
                   System.out.println( c1.next() );
              } // close for
         } // close main()
    } // close classAnd here is what is produced from running this:
    Local inner 0
    Local inner 1
    Local inner 2
    Local inner 3
    Local inner 4The string "Local inner" is passed to the method getCouter as a final String. getCounter creates the class and exits. Later a method in getCounter uses that final String "next". This is where I am lost - getCounter is done and gone, so how the heck is name accessible to the inner class?!?!
    Just when I thought I was getting the hang of this ;)

    So trying to redeem myself...
    You can use "javap -c" to see what a compiler is really doing.
    So using javap (version 1.4.2_04) on the inner class gives the following....
    class LocalInnerClass$1LocalCounter extends java.lang.Object implements Counter{
    LocalInnerClass$1LocalCounter(LocalInnerClass,java.lang.String);
      Code:
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   aload_0
       5:   aload_1
       6:   putfield        #2; //Field this$0:LLocalInnerClass;
       9:   aload_0
       10:  aload_2
       11:  putfield        #3; //Field val$name:Ljava/lang/String;
       14:  return
    public int next();
      Code:
       0:   getstatic       #4; //Field java/lang/System.out:Ljava/io/PrintStream;
       3:   aload_0
       4:   getfield        #3; //Field val$name:Ljava/lang/String;
       7:   invokevirtual   #5; //Method java/io/PrintStream.print:(Ljava/lang/String;)V
       10:  aload_0
       11:  getfield        #2; //Field this$0:LLocalInnerClass;
       14:  invokestatic    #6; //Method LocalInnerClass.access$008:(LLocalInnerClass;)I
       17:  ireturn
    The second method in the above is the next() method.
    The next() method uses the "getfield" bytecode to retrieve a member variable of the class which is named "val$name".
    The first method in the above is a constructor which takes a string as the only parameter. That string is saved in the member variable of the class called "val$name".
    It is preserving a reference, so if a StringBuffer was used rather than a String then one could alter the value in the for loop of the original code and see the change.

  • Question on Anonymous Inner class !

    Can an Anonymous Inner class implement or extend any thing?
    I feel no .. if yes can anyone give an example please..

    An example: the anonymous inner class in u extends Thread.
    $ cat u.java
    class u {
    public static void main(String a[]) {
    Thread t = new Thread ( ) {
    public void run() {
    System.out.println(getClass().getName());
    t.start();
    $ javac u.java
    $ java u
    u$1
    $
    The same idea but with the Runnable interface (and not class)
    $ cat u.java
    class u {
    public static void main(String a[]) {
    Thread t = new Thread ( new Runnable ( ) {
    public void run() {
    System.out.println(getClass().getName());
    t.start();
    $ java u
    u$1

Maybe you are looking for

  • Loops greyed out

    Hi, some loops are there but most are not? This happens sometimes and dont understand why? Thanks Rob

  • Is there a Lightning to Lightning cable ?

    I have a charger with a lightning connection, but the phone case that my spouse uses prevents setting the iPhone5 on top of it.  I need a cable with a female lightning jack to a male lightning plug (and the male plug can't be any larger than the norm

  • My mac pro laptop won't come on

    Not sure what to do about my new laptop that is about year and a half old. I use the power cord and it comes in faint and flashes green and a orange red color. I am at a lost. Please Help!!!

  • Menu elements in ABAP webdynpro?

    Hi, Is there any view elements available in ABAP webdynpro which is similar to Menu /Menu elements in other languages like VB or D2K? I want to create menu like this: Screen    Screen1(it will be view1 of component1)    Screen2(it will be view2 of co

  • Brushes are not working for lightnening

    My brushes do not work, for lightening.  I restet them and did control alt shift already.