Why I should declare a final object!

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. ");
When I complie the program there is one error as follow:
Problem.java:11: local variable timer is accessed from within inner class; needs
to be declared final
timer.cancel();
1 error
I don't kown why I must declare the timer as "final"!
Help me!

What you have is an anonymous inner class. For this class to be able to access local variables in the containing class they must be final. When the compiler compiles the code it will create the inner class with a reference to the variable. If you were able to change the variable the inner class would lose the reference.

Similar Messages

  • Why we should not declare a business method as final in EJBs - THX

    Why we should not declare a business method as final in EJBs - THX

    'cause it makes no sense at all and doesn't boost performance.
    regards
    dan
    scpj2

  • Why String class was declared as final.

    Why String class was declared as final.
    Thanks
    Mohan

    http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=d92720bd3ed4dffffffff95e59403ecf4db1:YfiG?bug_id=4095367

  • My MacBook Pro doesn't start; in safe mode shift CMD V the message "disk0s2: media is not present" is written on the screen repeatedly but the MacBook doesn't start.  Do you have any ideas of why this should be or what I should do to resolve this?

    My MacBook Pro doesn't start; in safe mode <shift CMD V> the message "disk0s2: media is not present" is written on the screen repeatedly but the MacBook doesn't start.  Do you have any ideas of why this should be or what I should do to resolve this?  Thanks  Eamonn

    Thanks for these suggestions: I have tried safe mode re-starts (both "verbose" and simple "shift" + power) to no avail.  I get the error message "disk0s2: media is not present".  Following this I inserted the installation disc and from there ran disc utility.  The "Verify Disk" indicated an error " invalid sibling link" which it could not repair.
    I also tried to completely re-format/erase the disk, but again got an error message "disk object invalid or unable to serialize".
    Any ideas of what could be causing this or the best solution?  I fear I am fast running out of options.

  • Why do we declare the variables private in a bean

    Hi,
    when we create a bean in the MVC architecture why do we declare the variables private. Also when do we use the access specifier private.
    Regards,
    Prashant

    pksingh79 wrote:
    Hi ^^,
    thanks for replying.I had a discussion with one of my trainers and he was of the opinion that the variables should generally be declared private. In this way we prevent classes from accessing and setting illegal values to those variables.
    Say for instance we have the class person as follows:
    public class Person
    int age;
    setAge(int age)
    if (age < 0)
    return null
    Person p = new Person() ;
    p.age = -2;
    //this would be perfectly legal
    //where as if we declare the variable as private as follows:
    public class Person
    private int age;
    setAge(int age)
    if (age < 0)
    return null
    Person p = new Person() ;
    // P.age = -2;   this would be illegal as age is private and would have to be accessed by the method defined above.
    p.setAge(-2);
    //the cbove line would retun null values.
    public class Person {
        private int age;
        public void setAge(int age) {
            if (age < 0) {
                throw new IllegalArgumentException("...");
            this.age = age;
    }

  • About Final Object

    Its possible to change the state of a final object .
    What is the idea behind this .. ?
    I am disturbed by this fact ..can any one tell me why?
    public class FinalTest
         public static void main(String args[])
              final MyFinal a = new MyFinal();
              a.x=1;
              a.y=1;
              a.callMethod();
              a.show();
    class MyFinal
         public int x = 0 ;
         public int y = 0 ;
         public void callMethod()
              x*=2;
              y*=2;
         public void show()
              System.out.println("x:= "+x+" y:= "+y);
    }

    Thanks for the clarifcation.
    Here is the summary..
    //FINAL OBJECTS STATE CAN BE MODIFIED.There's no such thing as a final object.
    //ITS WRONG TO SAY "FINAL OBJECT" BUT "FINAL OBJECT
    REFERENCE" IS THE RIGHT WORD.I'd say "final variable" is more correct, but at least "final reference" makes the crucial distinction between the object and the reference variable that points to it.
    //THE CONCEPT OF FINAL EXISTS FOR VARIABLES NOT FOR
    OBJECTS.Correct.

  • Instantiation of static final objects

    Is there a problem with coding the following?:
    class A {
    public static final A static_final_a_obj = new A ( B.static_final_b_obj );
    private B b;
    public A ( B b ) {
    this.b = b;
    class B {
    public static final B static_final_b_obj = new B ( A.static_final_a_obj );
    private A a;
    public B ( A a ) {
    this.a = a;
    I put log messages in each of the constructors to see if it would cause an infinite loop, but it doesn't seem to. The question is 'why'.. :) How can either of the static final objects ever be fully instantiated?

    Exactly. It is not executed infinitely.
    class A {
    public static final A static_final_a_obj = new A ( B.static_final_b_obj );
    private B b;
    public A ( B b ) {
    System.out.println(" A Cons");
    this.b = b;
    public static void main(String args[]) {
         System.out.println("A");
    Output:
    B Cons
    A Cons
    A
    class B {
    public static final B static_final_b_obj = new B ( A.static_final_a_obj );
    private A a;
    public B ( A a ) {
    System.out.println(" B Cons");
    this.a = a;
    public static void main(String args[]) {
         System.out.println("B");
    Output:
    A Cons
    B Cons
    B
    Edited by: prajeshps on Sep 18, 2007 1:51 PM

  • Why local class merely be final/abstract/package access?

    The scenario is that while declaring a local class as final/abstract/package access only and why this access specifier is using?
    could anyone plz express the reason for that?
    With Regards,
    Stalin.G

    final String efg = "efg";
    testCallback(new Callback()
    public void execute(String str)
    try
    Thread.sleep(3000);
    } catch (InterruptedException e)
    System.err.println(str+efg);
    System.err.println("finished " + System.currentTimeMillis());
    //...Look at the local variable efg, it must be final, or the code does not compile,, Can anybody explain why efg has to be final?*explained by dcminter and Jardium in [an older thread|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.

  • Why is there a strange grey object on the top left corner of my iPhone?I have included a photo

    Why is there a strange grey object on the top left corner of my iPhone? I have included a photo. It randomly appears and disappears.

    Hey Scott! Like I said, I thought I had done some damage -- even though the drop was just a couple of inches that was my very first thought, but when it came and went with which app I was in (or not) I knew it wasn't a damaged SCREEN.  So I wondered if it was a different damaged part, memory or some such.
    When I saw that others had the exact same shape, I could only imagine that perhaps the phone was indicating it was running a diagnostic, had been forcefully dropped, had a faulty/damaged accelerometer or some other purposeful object.  It clearly wasn't random, it was a definite shape.
    Hey Paul!  I'm hoping they've seen the issue and tried replacing a few parts or something...  Ya never know.  As a (mostly) retired guy I have the time!
    I also mentioned in a kind of oblique way that I had enabled the Kanji keyboard.  I should also mention that I have the field strength test enabled so that I am able to see the -db numbers instead of the antenna bars.  That's right in the same area, so it could be related.... maybe... or not. The screen was unlocked when this happened and I'm guessing I pushed a whole lotta buttons and/or icons as I was grabbing at it... I wonder if it is possibly an easter egg of some sort -- just the right combo of touches.  Then again, it bounced right on THAT corner... LOL 
    That's the only stuff I've ever done to the phone.  It's never been jailbroken or anything like that.  It has taken a few falls in its lifetime but none resulting in any obvious damage.
    It's a 32GB iPhone 3Gs and it is now 2 years old (bought June 27, 2009.) I'm just happy that it seems to be OK.  While Apple's stock may be the largest market cap in the US, my portfolio sure isn't.

  • Why I should use an iCloud mailbox?

    Hello there. I discovered that now I can use a @icloud.com mail address simply enabling it from my iCloud preference panel in OS X. I have created an email address, but I have some questions:
    What happens to my @icloud.com address if I don't use a Mac (or iPhone, iPad, etc.) anymore?
    Will my iCloud mail be available forever from icloud website or using IMAP configuration?
    What is the maximum space granted?
    The final question is: why I should use an iCloud mailbox instead (for example) of a Gmail one? All contributes will be greatly appreciated!

    1) Nothing
    2) Yes, as long as Apple keeps the service going
    3) 5Gb for free. More if you pay.
    4) It's up to you. iCloud email supports push notifications on iOS devices. That's about the only difference compared to any other IMAP email account. iCloud also syncs and backs up iOS devices.

  • Why we are going for ABAP Objects?

    Why should we use ABAP Objects instead of Function Group(in Function Module)?
    Moderator message: please search for available information/documentation before asking.
    locked by: Thomas Zloch on Oct 4, 2010 1:09 PM

    Before your thread will land on pile of locked ones, I would like you read [EIGHT REASONS WHY EVERY ABAP DEVELOPER SHOULD GIVE ABAP OBJECTS A SECOND LOOK|http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/37c5db90-0201-0010-3a9b-d0a5288f3c15]
    Regards
    Marcin

  • Iphoto on my macbook pro has stopped working. It comes up with a message saying that the library is either being used by another user or it is unreadable. Any ideas why I should be receiving this message?

    MacBook Pro 2009
    Model Identifier: MacBookPro5,1
    Processor  2.4 GHz Intel Core 2 Duo
    Memory  4 GB 1067 MHz DDR3
    Software  OS X 10.8.5 (12F45)
    Iphoto '11
    Iphoto on my macbook pro has stopped working. It comes up with a message saying that the library is either being used by another user or it is unreadable. Any ideas why I should be receiving this message?
    "Your photo library is either in use by another application or has become unreadable"
    Offered solution doesn't work:
    Shut down and restart your computer, and then open iPhoto again. If the problem persists, try rebuilding your photo library. To do this, quit iPhoto, and then reopen it while keeping the Option and Command keys pressed. You can also try restoring your photo library from a backup.
    I have already copied my photographs to the a library manager but when I tried to reuse iphoto and import the photos back into iphoto, it would not let me.
    I can't download photographs from my iphone or my digital camera.
    Any ideas on how I can solve this problem?
    There is a possibility that when I went to update applications that I started to install Mavericks which I then interrupted and cancelled. I am not definite that this caused this problem but it was at about the same time as when this problem started.
    Many thanks,
    Ed

    I have already copied my photographs to the a library manager but when I tried to reuse iphoto and import the photos back into iphoto, it would not let me.
    You can't "copy" your photos to the "library manager", there is just no way to any such thing.
    Option 1
    Back Up and try rebuild the library: hold down the command and option (or alt) keys while launching iPhoto. Use the resulting dialogue to rebuild. Choose to Repair Database. If that doesn't help, then try again, this time using Rebuild Database.
    If that fails:
    Option 2
    Download iPhoto Library Manager and use its rebuild function. (In early versions of Library Manager it's the File -> Rebuild command. In later versions it's under the Library menu.)
    This will create an entirely new library. It will then copy (or try to) your photos and all the associated metadata and versions to this new Library, and arrange it as close as it can to what you had in the damaged Library. It does this based on information it finds in the iPhoto sharing mechanism - but that means that things not shared won't be there, so no slideshows, books or calendars, for instance - but it should get all your events, albums and keywords, faces and places back.
    Because this process creates an entirely new library and leaves your old one untouched, it is non-destructive, and if you're not happy with the results you can simply return to your old one.  
    Regards
    TD

  • Why I should enter my credit card details if I just want to get free application?

    Starting from last month I am unable to download any free application which contains in app purchase service.
    Why I should enter my credit card details if I just want to get free application? I am close to go to Android

    I see, prepaid card is good solution but I don't want to share my card details at all. I can't download any
    application during a month due to this new feature with credit card verification and I am really close to switch
    to Nexus and go with Google. I don't want to do it but Apple forces me.

  • Why we should give currency type 30 in 2nd local currency ?

    Hi,
    why we should give currency type 30  2nd local currency in Define Currencies of Leading Ledger. Here 30 indicates EUR only. I want to give USD as 2nd local currency.
    Please suggest.
    Thanks,
    Gangaraju

    Group currency is unique at client level, i.e. this is same for all company codes.
    go to scc4
    Check the currency of your client.
    This currency comes by default for group currency and you can't give as your own.
    If you have any requirement, then you can give it as third local currency.
    Also remember third local currency you have to maintain at first country level.
    Rgds
    Murali. N

  • Any reason why I should use Safari on my PC

    I use Mozilla now. I now have an Iphone. Is there any reason why I should download and use Safari on my PC? I expect the functions will be different from IE or Mozilla or maybe better, but is it a good idea to download and use since I have an Iphone?

    It's pretty irrelevant, unless you really want to sync bookmarks from your computer to your iPhone (you could do that with IE as well, but not Firefox).

Maybe you are looking for

  • Error while opening Application URL

    Hi I have developed an ADF application and applies FORM based security.It works fine and asking for login and only authorized users are able to access application. All well in integrated weblogic. When I deploy this application on Managed server and

  • Problem in table cell editor

    Hai, I inserted as a dropdownkey in table, Parent node ABc is bind to table , the child node DEf bind to coloumn dropdownbyindex. i set child node singleton as false, but its giving null pointer exception. IXXXView.IABCNode iu=wdContext.nodeABC(); IX

  • PSE 12 on my windows pc and mac laptop

    Recently installed PSE12 on my new pc (windows 7 pro). I will be attending an editing course and just found out that I will require  my laptop (macbook pro). The macbook pro has my previous  PSE8 installed. Can I install my PSE12 on the mac also? Rea

  • I have a Cannon EOS 100 and cannot read CR2 files in camera raw. I need to know how to update the camera raw version in CS6

    I have tried to obtain an update from the web-site and uninstalled and re-installed CS6 but still have the problem.

  • Iframe doesnt show up in collapsible panel

    I have put a google calendar on a iframe I want to present on a collapsible panel. The Iframe doesent show up on firefox when the default state of the panel is closed. it works in Safari. Both on OS X. There is an errormessage from Fireworks pasted b