Why only final variables can be accessed in an inner class ?

Variables declared in a method need to declared as final if they are to be accessed in an inner class which resides in that method. My question is...
1. Why should i declare them as final ? What's the reason?
2. If i declare them as final, could they be modified in inner class ? since final variables should not modify their value.

(Got an error posting this, so I hope we don't end up with two...)
But what if i want to change the final local variable within that method instead of within anonymous class.You can't. You can't change the value of a final variable.
Should i use same thing like having another local variable as part of method and initializing it with the final local variable?You could do. But as in the first example I posted you are changing the value of the nonfinal variable not the final one. Because final variables can't be changed.
If so, don't you think it is redundant to have so many local variables for so many final local variables just to change them within that method?If you are worried that a variable might be redundant, don't create it. If you must create it to meet some need then it's not redundant.
Or is there any alternate way?Any alternate way to do what?

Similar Messages

  • Hi there, my phone was recently stolen and I'm gutted that I haven't backed my photos up on iCloud. Only my contact can be accessed. Is there any possible way of getting my photos back?

    Hi there, my phone was recently stolen and I'm gutted that I haven't backed my photos up on iCloud. Only my contact can be accessed. Is there any possible way of getting my photos back?

    Often when plugging a device into a computer (which has not been discussed if this has ever happened) one will be given the auto play option of transferring photos/data from the mobile device to the computer. Did you ever transfer the photos from your device to a computer?

  • Why the apple store is so expensive and why the apple users can't access for free after spending huge amount in apple phone ?

    Why the apple store is so expensive and why the apple users can't access for free after spending huge amount in apple phone ?

    The Apple store is correct. The warranty is not international, and Apple will not accept or return iPhones shipped from a different country.  You need to ship the phone to somebody in Hong Kong who can take it in to Apple for repair, or pay a third party repair shop in the Philippines to fix it.

  • Axis Fault: JavaProvider can not access a member of class Hello with mod.

    Hi,
    I am getting the following Axis Fault with content
    Exception in thread "main" AxisFault
    faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
    faultSubcode:
    faultString: java.lang.IllegalAccessException: Class org.apache.axis.providers.java.JavaProvider can not access a member of class Hello with modifiers ""
    faultActor:
    faultNode:
    faultDetail:
         {http://xml.apache.org/axis/}hostname:SNR143052
    java.lang.IllegalAccessException: Class org.apache.axis.providers.java.JavaProvider can not access a member of class Hello with modifiers ""
         at org.apache.axis.message.SOAPFaultBuilder.createFault(SOAPFaultBuilder.java:222)
         at org.apache.axis.message.SOAPFaultBuilder.endElement(SOAPFaultBuilder.java:129)
         at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)
         at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:633)
         at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanEndElement(XMLNSDocumentScannerImpl.java:719)
         at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(XMLDocumentFragmentScannerImpl.java:1685)
         at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:368)
         at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:834)
         at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
         at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:148)
         at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1242)
         at javax.xml.parsers.SAXParser.parse(SAXParser.java:375)
         at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
         at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
         at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
         at org.apache.axis.handlers.soap.MustUnderstandChecker.invoke(MustUnderstandChecker.java:62)
         at org.apache.axis.client.AxisClient.invoke(AxisClient.java:206)
         at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
         at org.apache.axis.client.Call.invoke(Call.java:2767)
         at org.apache.axis.client.Call.invoke(Call.java:2443)
         at org.apache.axis.client.Call.invoke(Call.java:2366)
         at org.apache.axis.client.Call.invoke(Call.java:1812)
    The client code for the webservice using instant deployment is
    import java.net.URL;
    import javax.xml.rpc.ParameterMode;
    import org.apache.axis.client.Call;
    import org.apache.axis.client.Service;
    import org.apache.axis.encoding.XMLType;
    import org.apache.axis.utils.Options;
    public class ClientHello {
         public ClientHello(){
         public static void main(String[] args) throws Exception{
              Options options = new Options(args);
              String endpoint = "http://localhost:" + options.getPort()+"/WebServices/Hello.jws";
              args = options.getRemainingArgs();
              Service services = new Service();
              Call call = (Call) services.createCall();
              call.setTargetEndpointAddress(new URL(endpoint));
              call.setOperationName(args[0]);
              call.addParameter("op1",XMLType.XSD_STRING,ParameterMode.IN);
              call.setReturnType(XMLType.XSD_STRING);
              System.out.print(args[1]);
              String s = new String(args[1]);
              String result = (String) call.invoke(new Object[]{s});
              System.out.println(result);
    The hello.jws is as follows
    class Hello {
         public String hi(String message){
              return "Hello "+ message;
    I am not sure why the message is substituted with "" instead of the parameter i have sent in args[1].
    Please help me out in this regard.
    Thanks,
    winkidzz

    Thanks swatdba.
    Any idea on how to proceed with implementing Webservices using Websphere MQ?

  • Reflection problem: can not access a member of class java.lang.IllegalAcces

    package org.struts.ets.utility;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import org.struts.bean.FieldTrouble;
    import org.struts.bean.GenericDAOBean;
    public class DynamicObjectCreation
         public static void main(String... args)
              FieldTrouble ft = new FieldTrouble();
              try
                   Class<?> c = ft.getClass();
                   //Class<?> c = FieldTrouble.class;
                   /*Class<?> c = null;
                   try
                        c = Class.forName("org.struts.bean.FieldTrouble");
                   } catch (ClassNotFoundException e)
                        e.printStackTrace();
                   Field f = c.getDeclaredField("var1");
                   //f.setInt(ft, 42); // IllegalArgumentException
                   f.set(ft, new String("A"));
                   System.out.println(ft.getVar1());
                   // production code should handle these exceptions more gracefully
              } catch (NoSuchFieldException x)
                   x.printStackTrace();
              } catch (IllegalAccessException x)
                   x.printStackTrace();
    }// If I put FieldTrouble.java in any other package than the current package I am running this code from. I get the following error:
    java.lang.IllegalAccessException: Class org.struts.ets.utility.DynamicObjectCreation can not access a member of class org.struts.bean.FieldTrouble with modifiers ""
         at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
         at java.lang.reflect.Field.doSecurityCheck(Unknown Source)
         at java.lang.reflect.Field.getFieldAccessor(Unknown Source)
         at java.lang.reflect.Field.set(Unknown Source)
         at org.struts.ets.utility.DynamicObjectCreation.main(DynamicObjectCreation.java:35)
    I tried all possible ways of creating class as:
    Class<?> c = ft.getClass(); OR
    Class<?> c = FieldTrouble.class; OR
                   /*Class<?> c = null;
                   try
                        c = Class.forName("org.struts.bean.FieldTrouble");
                   } catch (ClassNotFoundException e)
                        e.printStackTrace();
    Edited by: ..-__Kris__-.. on Feb 21, 2008 10:26 AM
    Edited by: ..-__Kris__-.. on Feb 21, 2008 10:26 AM

    Any hidden performance or memory issue here?
    Let us consider an object:
    public class SomeObject
         private String fieldA;
         private String fieldB;
         private String fieldC;
         private String fieldD;
         private String fieldE;
         //... say 50 declared fields....
         public SomeObject()
         public SomeObject(String fieldA, String fieldB)
              this.fieldA = fieldA;
              this.fieldB = fieldB;
    // getters and setters..     
    }When I create an object using the constructor with only two fields initialized such as the following code above, and look at what is happening to other fields as shown in the code below, I see that they are also AVAILABLE, now this is important, but they are set to null. What I wanted to know was, if I created an object with many fields, as many as 50 (getDeclaredFields = 50), and used a constructor with only two input fields to initialize an object, I still have 48 other fields available but set as NULL's. When I create more than 100,000 of these objects in a list and send to a .jsp page, I am unable to understand if this has more memory load than when you use a list of another object which has actually has only two declared fields in it. Each of this new object will have only two declared fields, when I say getDeclaredFields() it would return 2.
    This is where I am unable to figure out if this has anything to do with performance or memory, rather, what is the difference between the many possible ways you can initialize an object when there are too many fields which you probably won't use? Either create a new constructor with only two input arguments OR a generic constructor with all fields as input arguments but all those fields which you won't use assigned NULL's OR create another new object with only two declared fields
    SomeObject someObj = new SomeObject("abcd","cdef");
              Field[] fields = someObj.getClass().getDeclaredFields();
              System.out.println("Number of available fields: " + fields.length);
              for(int i = 0 ; i < fields.length ; i++)
                   try
                        fields.setAccessible(true);
                        System.out.println("Field " + i + ", with value: " + fields[i].get(someObj));
                        fields[i].get(someObj);
                   } catch (IllegalArgumentException e)
                        e.printStackTrace();
                   } catch (IllegalAccessException e)
                        e.printStackTrace();
              }Edited by: ..-__Kris__-.. on Mar 23, 2008 5:04 PM
    Edited by: ..-__Kris__-.. on Mar 23, 2008 5:05 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Can not access a member of class Test with modifiers ""

    Hi!
    I am trying to get a application into a applet, but I just get this errormessage:
    Exception: Java.lang.IllegalAccessException: Class sun.applet.AppletPanel can not access a member of class Test with modifiers ""
    Anyone that have any idea whats wrong here?
    Best regards Raymond

    Post class where the exception was ocurred.

  • HELP! SL stuck in final restart - can't access IMAC

    just installed SL 'Family Pack' on my Macbook - all good.
    Tried on the IMAC - unfortunately there were 'software updates' ready to go but the install had started. When it got to the first restart it was stuck in 'updates'. So I 'checked for more updates' and then restarted. Once restarted, the SL install icon showed the install had resumed after the restart.
    Then at the CONGRATS prompt for the last restart, my IMAC never completed the restart and has been stuck there for over an hour. I rebooted - still stuck. Can't access the imac and dont know how to 'undo' or 'redo' whatever needs to be done. Managed to 'tickle' the disc out of the computer in case the reboot was stuck with the disc. Still no luck. GANT USE MY IMAC! HELP!
    JJ

    Anyone?
    I finally managed to download the newest combo update and installed it successfully!
    However Safari still doesn't open. It keeps saying the following:
    Check with the developer to make sure Safari works with this version of Mac OS X. You may need to reinstall the application. Be sure to install any available updates for the application and Mac OS X.
    I also finally got access to App Store: but the download of Mountain Lion doesn't complete, because it seems to need Safari.
    So I'm still stuck with the two issues:
    i) Safari doesn't work, and I can't get it to work unless I can reinstall/upgrade the OS.
    ii) I can't upgrade the OS without Safari!
    --- unless someone knows a way to install Lion/Mountain Lion _without_ Safari??
    Thanks for all your help!

  • How can I Access the Flash "Slide class" using flex and ActionScript 3?

    Hi,
    I hope someone can help me solve a problem...
    I'm using the flex SwfLoader to load a flash side
    presentation as follows...
    <mx:SWFLoader id="ss_slides" source="ss_slides.swf"
    width="320" height="240"/>
    I would like to access the flash "Slide Class" using flex so
    I can make the following call...
    Slide.gotoNextSlide();
    Anyone know how I can do that?
    Would it be through the SwfLoader Object?
    Is there another way?
    F.Y.I. Here is a snippets about the Slide class from the
    Flash 8 help...
    Using the Slide class (Flash Professional only)
    You use the methods and properties of the Slide class to
    control slide
    presentations you create using the Screen Outline pane for a
    Flash Slide
    Presentation, to get information about a slide presentation
    (for example, to
    determine the number of child slides contained by parent
    slide), or to navigate
    between slides in a slide presentation (for example, to
    create "Next slide" and
    "Previous slide" buttons).
    You can also use the built-in behaviors that are available
    in the Behaviors
    panel to control slide presentations. For more information,
    see Adding controls
    to screens using behaviors (Flash Professional only) in Using
    Flash.
    Thanks,
    Chris S.

    Hi Chris,
    You cannot access the methods of the Flash 8 movie from Flex.
    And you can't do it the other way around either.
    The only way to communicate is to create a LocalConnection on
    each side.
    M.

  • Can enclosing instance for an inner class be null?

    I have a class Solution, which defines an inner class, SolutionStep.
    In a third class I construct several SolutionStep objects, and later use them to construct a Solution.
    In this third class I have statements like this:
    Solution solution = null;
    aCollection.add(solution.new SolutionStep(arg1, arg2);
    This has been working fine, but recently a customer reported an error,which seems to be a NullPointerException at the line above.
    Now that I look at this code, I'm not very happy about it and I'll clean it up, but I am left with the basic question of whether what I'm doing is legal. Can the enclosing instance used to construct an inner class be null? I have not been able to find a definitive answer.
    Any help appreciated.

    Yes, you're right, I dropped a parenthesis. Sorry.
    The offending statement is actually
    aCollection.add(solution.new SolutionStep(arg1,
    arg2));
    And that is certainly legal. The inner class does not
    need to be qualified when it's constructed in the
    context of an enclosing instance.Very interesting.
    The following code demonstrates this....
        class Solution
            class SolutionStep
                public SolutionStep()
        public class ThirdClass
            static public void main(String[] args)
            Solution solution = null;
            //Solution solution = new Solution();  // This produces no null exception.
            Solution.SolutionStep s = solution.new SolutionStep();
    Using jikes and javac doesn't change the behavior so that means it is VM rather than compiler specific.
    I am using 1.4.2_04 on windows and I get the null pointer exception.
    Looking at the javap output suggests that invokespecial has to be checking this (although I could have overlooked something when I checked.)
    This probably comes from the following in the VM spec under invokespecial...
    Otherwise, if objectref is null, the invokespecial instruction throws a NullPointerException.

  • Why do I get "can't access device" message while using Safari?

    I am traveling in Mexico with my friend who has a Sony Vaio running Vista. I have a white MacBook (early 2008) running OS X 10.5.6. We choose hotels offering wireless internet, and my friend has no trouble anywhere, where I have trouble everywhere. BIG disappointment, since I'm always bragging on Apple. I have the feeling I my have done something dumb with the internet connection utility in "System Preferences"- could that be it?
    Some questions about what has been happening:
    A) why does "internet" (the utility in sys pref) sometimes tell me that I am connected when Safari says I am not?
    B) Other times it tells me I'm not connected when Safari is the process of connecting successfully.
    C) Why does it say I need a password when I don't? THIS IS THE MOST CONSISTENT MISTAKE IT MAKES
    D)When I do need a password it often says "password invalid" when I type correct one.
    E) I get "could not open communication device" WHILE Apple.com is actually loading! and even after I have been using it for 5 or so minutes.
    Finally, if I have to re-install Safari, can I do it on line? (provided I can get on line).

    Try resetting the App Store.
    App Store Reset       Learned from Old Toad

  • Why only 1 form can be running at the same time?

    Hello guys,
    I wonder if you can help me..
    At the company i work in, some application has a problem where the same applicatoin can not be opened if there are already somebody else opening the same application. what is the cause of this behaviour?
    another problem is some computer generate SSL integration error messages when trying to open an application. While at other computer the application run fine. Any idea why this happen?
    thanks in advance

    At the company i work in, some application has a
    problem where the same applicatoin can not be opened
    if there are already somebody else opening the same
    application. what is the cause of this behaviour?A record is probably locked. This can happen when one user is updating a record and another user tries to update the same record before the first user is done (committed the record).
    another problem is some computer generate SSL
    integration error messages when trying to open an
    application. While at other computer the application
    run fine. Any idea why this happen?Hard to say without knowing the error message.

  • I have upgraded to 10.6.8 on my macbook pro and find I don't have pages.  Pages in app store is for 10.10 only.  How can I access all my pages files in Snow Leopard?

    I have upgraded to 10.6.8 Snow Leopard from Leopard on my macbook pro and now cannot read and write pages.  Pages in app store is for 10.10 and above.  I don't have a pages application. Where can I get pages for snow leopard?

    It's been so long since I bought my macbook pro in August of 2010, but I do remember the iwork disk that had pages, numbers, and keynote on it, but I can't find the disk in my closet.  I did not realize that when I took my computer in to the genius bar to upgrade to Snow Leopard, and then to download Yosemite, that I would lose these applications.  I had no reason to open pages when I emptied my hard drive to upgrade to Snow Leopard, so I don't know if I kept iwork when I upgraded to Snow Leopard at the Genius Bar.  I had file vault on with my external drive on, and since removed it before the upgrade, but now all my documents are unable to open on my external drive.  ****.  So now the new problem is how do I undo file vault in a new OS 10.10 when encoded in 6.8?  Can I take my external drive in to Genius Bar?  
    I bought my macbook pro at Best Buy, but can't remember if iwork came with this computer, or with an older mac I bought.  Can anyone check to see if I have a valid key code, and will insertion of an iwork disc allow me to use pages with Yosmite?

  • Am I the only one who can't access gmail via Safari?

    I am on 10.5.8 and Safari 5.0.6 and must wait 15 to 20 minutes before the address field progress bar gets to http://www, other online sevices [ like going here ] work well. Has anyone else seen this?

    Also...
    "Visual Voicemail is currently unavailable" and my Greeting button is grayed out and deactivated.
    I can call in to check it just fine but VisVM is not working either.
    FYI...
    ::LL::

  • Why Inner class cannot access static variables

    Why is it that inner class can use only static final variables of the outerclass, and not ordinary static variables of the outer class. "Yes the JLS sepcifies that only final static variables can be used inside an inner class, esp a non blank final variable". But why this restriction.
    Thanks.

    so what are final static variables treated as if they
    are not variables. So if the final static value is
    not loaded when the class is loaded how will the
    class know about the value.??The actual value wil be substituted for the name of a static final value at compile time. That's why you can use them in switch statements where you can't use any variable variable.
    This is something to watch out for, by the way, because if you use a public static final value from one class in another the actual value will be compiled into the using class, so if you change the value where it's defined the class using it will have the old value until it's recompiled.

  • Final in inner class

    I am trying to manually make a drawing program similar to this one
    http://javafx.com/samples/Draw/
    However I am running into issues involving inner classes and finals.
    "local variable size is accessed from within inner class; needs to be declared final"
    It wants me to make either SIZE or size a final. However once final, I can't change the variable.
    I have often used the variable in a for loop to assign a value(though maybe it was a bad practice?) however I am not sure the best way to handle this.
    Any suggestions?
    Thanks!
    int SIZE = 1; //somewhere else
            for( int size = 0 ; size < 5 ; size++){
                  Circle circle = new Circle(D/Padding);
                  circle.setOnMousePressed(new EventHandler<MouseEvent>(){
                      public void handle(MouseEvent me){
                          SIZE = size;
             );edit:
    I am well aware this isnt neccesarily a javafx specific thing, but more of a general java poor programming knowledge.
    I also know that the mouseadapter is an anonymous class and can only access final.
    I am just looking for any suggestions on how to best handle this.
    Edited by: namrog on Jul 5, 2011 10:51 AM
    Edited by: namrog on Jul 5, 2011 10:59 AM

    namrog wrote:
    I am trying to manually make a drawing program similar to this one
    http://javafx.com/samples/Draw/
    However I am running into issues involving inner classes and finals.
    "local variable size is accessed from within inner class; needs to be declared final"
    It wants me to make either SIZE or size a final. However once final, I can't change the variable.Yes, that's the point. If a local variable is to be used by an instance of a nested class, that nested instance can live on long after the local variable goes out of scope. So it needs its own, separate copy of the variable. However, since, as far as we are concerned, there is only one variable, that variable needs to be final, so that there will not be issues with keeping the two copies' values coherent.
    I have often used the variable in a for loop to assign a value(though maybe it was a bad practice?) however I am not sure the best way to handle this.
    Any suggestions?Create a final variable and copy the value of your non-final variable to it.
    int nonFinal =...;
    final int theFinalCopy = nonFinal;
    new Whatever() {
        void doStuff() {
          doSomething(theFinalCopy);
    }

Maybe you are looking for

  • Getting the Outstanding Trade Receivables of a Customer

    Hi SAP Experts, I am trying to make a report to show the outstanding trade receivables of a customer based on his payment terms. I have a few questions I want to ask to all of you: 1. Can a direct FI invoice for a customer be partially collected? If

  • Reporting Swap Space Usage

    I own a piece of software that reports three Solaris swap space statistics: Available Used Total It uses the swapctl API to gather the data. One user reports that this is insufficient because Solaris uses a combination of disk space (reported by swap

  • PB wakes up to grey screen

    Recently my MacBookPro3,1 has started waking up occasionally to grey screen. Very had to get it to respond even using the power button. I have the latest system software on an 800GB partition on my western digital 1TB internal drive and 4GB ram. Alwa

  • UIX Custom table layout with ADF Bindings

    hello, Please point me to examples of binding ADF data controls on UIX table and also the UIX table layout with different row and col spans. Thanks in Advance.

  • STR to STO conversion fine with ME59 but not ME59n ????

    Hi Guys, We are planning on moving to ME59n for PR to PO conversion. When I try to convert STR to STO with ME59n  it is giving me the error message ; - Item category U not allowed with document type - Doc. type UB should be used for suppl. site DC06