Constants:  "final static" vs. "final"

In a GUI object, I have some class constants that are only used internally. Example 1:
private final int PREFERRED_WIDTH = MainWin.MAX_WINDOW_WIDTH;
private final int PREFERRED_HEIGHT = 50;Example 2:
private final JButton helpButton = new JButton("Help");
private final JButton closeButton = new JButton("Close");
private final JLabel clearanceLabel = createClearanceLabel();Should the members in EX1, EX2 be static??
These items are members of a GUI object, and there is only 1 instance of this GUI object during application runtime.
The nature of my question is about the best practices of when to use the "static" modifier for private class constants.
Thank you
Message was edited by:
PatrickFinnigan

and "static" as sparingly as possible -- Disagreement here. First, of course, use it when
appropriate. Second, though, my customers coding
guidelines urge to use static for all methods that
aren't accessing non-static members; there might be a
reason for that although I don't know. But it's
basically no problem declaring those as static.I can see the logic of declaring them static if they don't access anything instance-level; at least it makes it more obvious what it's doing. I suppose you might want to keep it non-static if you think that at some point the implementation will change and you don't want users of the API locked into a way of calling it which won't work, but such thinking can be dangerous.
On a related note, a bad design choice I sometimes see is an excessive use of objects in which there is absolutely no state being maintained; the code in question doesn't need to be non-static at all. Making things objects when they don't have to be can make things too complicated.
On the other hand, when you're doing object-oriented programming and you find that you're never creating objects, then something is seriously wrong.
I think the best rule of thumb is: keep a clear understanding of what's an object, what isn't, and why; keep objects and non-objects clearly built as such, don't make things that are basically static utility methods into objects just because you can; and if you find that you're throwing the keyword "static" around a lot, then it's a red flag that you've probably got something wrong in your design.

Similar Messages

  • Why a Constant has to be of type Static final  rather than final?

    Hi,
    I struck up with a basic doubt
    Why a Constant has to be of type Static final rather than final?
    Hoping for quick reply
    Venu.

    Hi,
    I struck up with a basic doubt
    Why a Constant has to be of type Static final rather
    than final?It doesn't have to be, but it usually makes more sense for it to be static (associated with the class) than non-static (associated with the instance). If every instance of the class will have the same value for that variable--whether it's final and a constant or not--it makes sense to make it static. There's no need for multiple copies of the same value. (And in the case of non-final variables, it can lead to incorrect program behavior if it's not static.) If each instance of the class could potentially have a different value for that variable, then it has to be non-static.

  • Discussion: private final static vs public final static

    take following class variable:public final static int constant = 1;Is there any harm in making this variable public if it's not used (and never will be) in any other class?
    Under the same assumption Is there any point in making this variable static?
    tx for your input

    Is there any harm in making this variablepublic
    if it's not used (and never will
    be) in any other class?Harm? No. Use? Neither.I suppose it makes no difference at all concerning
    runtime performance?
    Under the same assumption Is there any point inmaking this variable
    static?If the creation of the constant is costly, for
    instance. A logger is private final static most of
    the time.Same here, does making a variable final or static
    have any influence on runtime performance?No. And for 'expensive' operations (say, parsing a XML configuration file, which only needs to occur once), making a variable static will improve performance.
    - Saish

  • How to javadoc "public final static int"?

    How can we create "Field Summary" HTML document for "public final static int" variables?
    This question is probably same as the below question.
    http://forums.java.sun.com/thread.jsp?forum=41&thread=72832
    p.s.
    The below document indicates CENTER, NORTH, ...
    How an we achieve it to document "public final static" variables?
    http://java.sun.com/products/jdk/1.2/docs/api/index.html

    No, 1.3 does not have the static constant values exposed to the Doclet API,
    and so that information is not available to any doclets to place in the
    generated documentation.
    BTW, based on feedback from a developer, we changed the format from:
    public static final int NORTH = 0
    to
    public static final int NORTH
    See: Constant values
    where the "Constant values" link takes them to a summary page that
    lists all of the values. This helps discourage users from mistakenly
    seeing and using the value instead of the constant.
    -Doug Kramer
    Javadoc team

  • Actual Benefits of final methods and final parameters

    I know that a lot of this depends on the JVM and the actual code, but I was wondering what the actual real world advantage was of using final methods and final parameters.
    I use a business and data layer for my program to interact with the database. So all of the methods in these classes are public and static. I was just wondering if it would be benefical to make all of these methods final and all of the parameters final also. I won't ever be making subclasses of these classes, so is this worth doing?
    Thanks,
    Dave Johansen

    On the point of final, this should always be a design decision. That is, does it make sense to allow your class to be overridden? Making classes and/or methods final is a big barrier to future enhancements and extendability - so only make soemthing final if you haver a specific reason for doing so.
    Any performance issues should not take a high precedence in this decision - and in any case the difference in making something final will be non-existant for all practical purposes.
    How about volatile?
    I get the meaning of synchronized but
    volatile?Volatile is a keyword that tells the JVM it can't optimize / inline serctions of code that use certain variables. You may not realise it, but the JVM takes your bytecode and chops them up and re-arranges them at runtime, to boost performance. This can sometimes have dangerous consequences in a mutlithreaded environment, so by adding the volatile keyword you are saying to the JVM (or specifically HotSpot) not to perform any "code magic".
    Here's a simple example:
    public class TestClass {
        private boolean check = false;
        public void setTrue(){
            check = true;
        public void check(){
            check = false;
            if(check){
                System.out.println("Will this ever print?");
    }Obviously the string will never print in a single threaded environment. However, in a multithreaded environment, is is possible that a thread could call setTrue() between another thread setting the value to false and performing the if() check. The point is that due to runtime optimization, Hotspot may realise that check is always false, so completely remove the code section with the if block. so regardless of the value of the boolean, the code may never be entered.
    One solution is to declare the boolean check as volatile. This tells the JVM that such optimizations are not allowed and then it is entirely possible for the string to be printed.
    One curiousity, off-topic:
    is there a way for jvms instantiations to see each
    other?Have you looked into RMI?

  • Final method and final class

    What is final method and final class in abap objects.

    ejp wrote:
    Since that doesn't work--or would overyy complex to implement... would be impossible to implement. Once the method-local copy goes out of existence, ipso facto it can never be changed. This is the whole point.I consider it impossible too, but I'm not a language/compiler/runtime expert, so I allowed for the possibility that there could be some way to do it--e.g. local variables that are references in inner classes live on the heap instead of the stack, or something. My point isn't that it's possible, just that if it were somehow to be done, it would by ugly, so we may as well consider it impossible--it just ain't gonna happen.
    we go with the logic, "Okay, we need to copies, but keeping them in sync is a nightmareNo, it is +meaningless.+No, it's not meaningless. If we have the two copies, and they're not final, then after the inner object is created, the method can continue running, and either the method or the inner object could modify its copy. As far as our code knows, it's the same variable, so there'd have to be some way to keep them in sync. That's either impossible or undesirably complex--like the above, it doesn't matter which--so it's final in order to get past the issue of keeping the copies in sync.

  • To Flag PO for final delivery or final invoice if contract expires

    HI Experts,
    whenever the validity date of outline agreement is expired and there is a PO created with ref to the same Outline Agreement, the system does not allow to flag for the final delivery or final invoice for the PO, so that there can no further processing for the PO.
    We just want only to close the PO (by setting flag final delivery or final invoice).
    Please advice
    Lipika

    HI,
    When Purchase order is created with reference to contract, system carry
    out the check whether Document date of PO should be within contract
    "validity start" and "vaidity end" date. If document date is outside
    the "validity start" and "validity end" date of PO, message 06 040
    "Validity period of contract does not start until &" or message
    06 041 " Validity period of contract expired on &" is raised.
    Same check is also carried out during any change in PO (txn ME22N).
    Please use one of following option to close the PO.
    1. Change the category of message 06041 as warning in customization.
    Txn OLME.
    Environment Data -> Define Attributes of System Messages ->System
    Messages
    2. Change the validity end date in contract and close the Purchase order. Validity end date can be reverted.
    BR
    Nadia Orlandi

  • Final Cut Pro & Final Cut Pro HD?

    Hi,
    I always tought that Final Cut Pro & Final Cut Pro HD were the same.
    Of course I understand that there is a difference in the HD feature.
    On the website from Apple - Pro Applications, Final Cut Studio, it says that FCP has the HD feature.
    I have FCP 5.0.4. Is this the HD version? And if so, Why the difference in the name?

    Its primarily a marketing thing .. nothing to really be concerned about.
    FCP was Final Cut Pro up through version 4. With the introduction of the 4.5 update, it became Final Cut Pro HD, due to the addition of support for DVCProHD.
    Since the many varieties of HD have become so commonplace, its now just called Final Cut Pro 5 and only available in the Final Cut Studio Package.
    -DH

  • Loading the final static variables at run time.. Please help

    Hello, fellow developers & Gurus,
    Please help me figure out the best way to do this:
    I need to load all my constants at run time. These are the public static final instance variables. The variables values are in the DataBase. How do I go about loading them.

    Your original question was diffeent, but your further posts show what you really want to do:
    1) all constants in 1 class
    2) available readonly for other classes
    3) updatable during runtime by changing in the database
    Did I understand you right?
    Then smiths' approach solves point 2):
    Instead, make the variables available through a method
    call - that way you avoid the whole final variable
    versus read-only attributes problem.
    //GLOBAL VARIABLES EXPOSED AS PUBLIC PROPERTIES
    public final class GlobalProperties
    public static int getTableSize();
    public static int getRowSize();
    Each "constant" should be a private static variable, and these methods simply return their values.
    The variables are initialized in a static initializer by accessing the db. Ok.
    You habe a table with one row containing as columns all the constants.
    A method readConstants() does a "select constant1, constant2, ... from const_table" and sets all the variables.
    The static initializer calls this method.
    Right?
    Ok, then you simply call readConstants() everytime you want to synchronize with the actual content of const_table.
    Was it this?

  • Static and final modiers

    Brief summary: I want to make the JButtons, JLabels, and JPanels public static final. Is that bad, and why? And what the heck is the Java system doing when it compiles and runs a program that does this? Is the code more efficient?
    More questions below.....
    I'm new to making GUI designs with Java. I am going to school and my teacher is making us do GUI interfaces in JAVA.
    Early on, I learned that constants are identifiers similar to variables except that they holda particular value for the duration of their existence. QUESTION ONE: what happens during run-time, how does JAVA handle this constant?
    I also learned that some methods may be invariant, as with a simple extension. These methods should be marked final. The subclass inherits both a madatory interface and a mandatory implementation. So I guess you use a final method when you want to model to a stric subtype relatinoship between two classes. All methods not marked final are fair game for re-implementation.
    Well, that's good and well. So then I started thinking about static. That's a keyword in Java and when used with a variable, it's shared among all instances of a class. There is only one copy of a static variable for all objects of a class. So then again, I noticed that the programs in my book that used final usually threw in the word static before it. Memory space for a static variable is established when the class that contains it is referenced for the first time in a program.
    Well, that too is great? Question 2: In my GUI programs, can I declare all the buttons (JButtons), labels (JLabels), panels (JPanels) as being final constant static?
    In the program I don't intend to change the type of button, or JPanel so why not make it a constant? As long as I'm doing it, why not make it static? WHAT IS ACTUALLY GOING ON THEN IN MY PROGRAM WHEN I DO THIS?
    Question 3: What goes on in JAVA when I make a method or function public static final. Is that what the Math class does? How is that handled during run-time? Is the code faster? Is it more efficient?
    Question 4: If I make a class final, that means a subclass cannot extend it? Or does it mean that a subclasss cannot change it? I know that if the function or method in the parent class was final, then the subclass inherits both a madatory interface and a mandatory implementation....So if the class is final, then what?

    Final makes a variable a constant. You can not change the variable once it has been initialized. A final method cannot be overridden in subclasses. So I would not make any button or menu item final unless you never want to change it. Final should be used to protect data. I don't believe there is a performance difference if they are used.
    Static variables exsist only once. So if you have a class with a static variable and create several instances of that class the static variable will be the same in all of them.
    Again data protection. Static variables are useful but a pain to use. I don't think there is a performance advantage with using them.

  • Static and final keyword questions

    Brief summary: I want to make the JButtons, JLabels, and JPanels public static final. Is that bad, and why? And what the heck is the Java system doing when it compiles and runs a program that does this? Is the code more efficient?
    More questions below.....
    I'm new to making GUI designs with Java. I am going to school and my teacher is making us do GUI interfaces in JAVA.
    Early on, I learned that constants are identifiers similar to variables except that they holda particular value for the duration of their existence. QUESTION ONE: what happens during run-time, how does JAVA handle this constant?
    I also learned that some methods may be invariant, as with a simple extension. These methods should be marked final. The subclass inherits both a madatory interface and a mandatory implementation. So I guess you use a final method when you want to model to a stric subtype relatinoship between two classes. All methods not marked final are fair game for re-implementation.
    Well, that's good and well. So then I started thinking about static. That's a keyword in Java and when used with a variable, it's shared among all instances of a class. There is only one copy of a static variable for all objects of a class. So then again, I noticed that the programs in my book that used final usually threw in the word static before it. Memory space for a static variable is established when the class that contains it is referenced for the first time in a program.
    Well, that too is great? Question 2: In my GUI programs, can I declare all the buttons (JButtons), labels (JLabels), panels (JPanels) as being final constant static?
    In the program I don't intend to change the type of button, or JPanel so why not make it a constant? As long as I'm doing it, why not make it static? WHAT IS ACTUALLY GOING ON THEN IN MY PROGRAM WHEN I DO THIS?
    Question 3: What goes on in JAVA when I make a method or function public static final. Is that what the Math class does? How is that handled during run-time? Is the code faster? Is it more efficient?
    Question 4: If I make a class final, that means a subclass cannot extend it? Or does it mean that a subclasss cannot change it? I know that if the function or method in the parent class was final, then the subclass inherits both a madatory interface and a mandatory implementation....So if the class is final, then what?

    You have a lot of questions..
    You make a method final if it should not be allowed for subclasses to override it.
    If you make a class final, you will not be able to subclass that class.
    A static method is a class method, i.e. you don't need to create an instance of the class to call the method.
    You can make any object and primitive final, but for objects, you are still able to modify what is inside the object (if there is anything you can and are allowed to modify), you just can't change the final reference to point to another object.
    When you make a variable final, you sometimes make them static as well if they should work like constants. Because there is no reason that every instance of the class has their own copy of constants.
    If you make everything static, why even bother to work with object-oriented programming. It gives you no reason to make instances of your classes. You should try not to make static variables and methods when there is no need for it. Just because you start from a static main method, it doesn't mean it is necessary to make all variables and methods static.
    Don't think so much about performance issues as long as you are still learning java. When you make a method final, it is possible for a compiler to inline that method from where you call the method, but you will hardly gain much in performance with that. In most cases it's better to optimize the code you have created yourself, e.g. look at the code you run inside loops and see if you can optimize that.

  • Compiler replaces final static

    Hi!
    I've got the following problem:I need to check the version of an external jar which is contained in an attribute number of of class called Version. The problem with this is that the attribute is static final and therefore is replaced at compile-time with the current value. How can I prevent that to get the value of the class used at runtime?
    Changing compiler options? Or is there any possibility to tell java not to replace code segments during compile time?
    Any ideas?
    Thanks!

    Although i'm definitely having a hard time deciphering
    exactly what the problem is, it seems to be a result
    of the fact that compilers will replace static finals
    at compile time. Basically, if you had the following
    setup
    public class A
    public static final int FOO = 1;
    public class B
    public B()
    System.out.println("Foo: "+A.FOO);
    }Then when you compile class B, it's going to
    actually replace the value of A.FOO with 1, rather
    than leave a reference to the value in class A. A
    result of this would be that if you changed the value
    of FOO and recompiled class A, you wouldn't see any
    changes in class B until that class was also
    recompiled.
    Precisely - this is the problem the OP is having. However, I'm suggesting this can be solved by using reflection.

  • Final static array declaration

    Hi,
    I recently discovered i can do this
      protected static final float[] COLOR_BUTTON_FRAME_OUTLINE = { 0.5f, 0.5f, 0.5f };rather than
      protected static final float[] COLOR_BUTTON_FRAME_OUTLINE = new float[] { 0.5f, 0.5f, 0.5f };is there a difference or is it just a shortcut?

    just so you now, it only works when the variable is declared and defined simultaneously. I.E.
    int[] a = { 0, 1, 2 };works, but
    int[] a = whatever;
    a = { 0, 1, 2 }; // redefine adoes not. For that you must do
    int[] a = whatever;
    a = new int[] { 0, 1, 2 }; // redefine a

  • Problem compiling with a  final static statement

    I'm trying to compile a code that i obtained from jad. The error is:
    MethodInvoke.java:269: illegal start of type
    ^
    At the final of the code i got:
    static final
    {                //here appear the problem
    try
    pool = new ObjectPool(com.test.wsp.main.MethodInvoke.class);
    catch(Exception exception)
    throw new ExceptionInInitializerError("could not initialize the worker pool, exception=" + com.tess.hometop.gateways
    .utils.Utils.parse(exception));
    Could anyone explain me which is the problem?
    Thanks

    I'm trying to compile a code that i obtained from jad. The error is:
    MethodInvoke.java:269: illegal start of type
    ^
    At the final of the code i got:
    static final
    {                //here appear the problem
    try
    pool = new ObjectPool(com.test.wsp.main.MethodInvoke.class);
    catch(Exception exception)
    throw new ExceptionInInitializerError("could not initialize the worker pool, exception=" + com.tess.hometop.gateways
    .utils.Utils.parse(exception));
    Could anyone explain me which is the problem?
    Thanks

  • Final output of Final Cut Express HD 3.5 is blurry and out of focus.

    Using clear/sharp '.mov' files as clips. Doing simple editing, nothing fancy. When I finally output the project using 'Export/Using QuickTime Conversion,' the final is blurry and out of focus. I've tried every compression type (H264, Animation, etc.). Same problem. Anyone know why this is happening?
    Although the specs for my computer are well within the Final Cut Express guidelines (I've even upgraded my graphics card to a Radeon 9800 Pro 256 MB), I'm still thinking that perhaps the G4 I'm using doesn't have enough juice to run the FCE software. By the way, I don't have any other programs active when using FCE. Any help on this would be greatly appreciated. Thanks.
    G4 (Mirror Drive Doors)/1.25 GHz/2.0 GB Memory/Radeon 9800XT (256 MB) Mac OS X (10.4.9) 2 Internal 120 GB Hard Drives (RAID)/2 CD-DVD Drives: Super Drive & Combo Drive
    G4 (Mirror Drive Doors)/1.25 GHz/2.0 GB Memory/Radeon 9800XT (256 MB)   Mac OS X (10.4.9)   2 Internal 120 GB Hard Drives (RAID)/2 CD-DVD Drives: Super Drive & Combo Drive

    Thanks for your response.
    Here's what I'm (trying) to do:
    I'm creating short 5 minute tutorial movies that will be distributed as QuickTime movies (burned to disk) for short run distribution (college).
    Here's the process: the movie itself is a recording of monitor screen actions recorded (audio and video) using Snapz Pro movie mode. The recorded size is 800 x 600. There might be 5 such 1 or 2 minute clips. The quality is excellent. I bring them in to FCE, drop all the clips on the same track, and add simple transitions. That's it.
    Now I need to somehow get a final QuickTime movie, with close to the same quality I had in the clips.
    So... I take the FCE file, output it using 'Export>QuickTime Conversion,' using the same size I originally recorded in, 800 x 600. Tried every codec available. Every time, the end result is a very blurred version of the original Snapz Pro recordings.
    I've even tried outputting the FCE file as 'Export>QuickTime Move' (not using the conversion method). Opened that up in QuickTime Pro with the same result: blurred and out of focus.
    I'm viewing the exported file in QuickTime Pro, with the 'Movie Properties' setting of 'High Quality.'
    Any clue? This is driving me crazy. But I'm determined to get this right.
    G4 (Mirror Drive Doors)/1.25 GHz/2.0 GB Memory/Radeon 9800XT (256 MB) Mac OS X (10.4.9) 2 Internal 120 GB Hard Drives (RAID)/2 CD-DVD Drives: Super Drive & Combo Drive

Maybe you are looking for

  • How can I convert a Word document to an ePub document?

    I would like to convert a Word document of a book I've written to an ePub version that my son can load it into his iPad to read.  Anyone know if there's a way to do that on my Mac mini computer, or if there is a program I can download that will do it

  • How do folks like the "feel" of the iPhone 5 in their hand?

    I went to the Apple store today to "feel" the new iPhone.  My previous phone is the 3GS iPhone and I have loved, that rounded contour in my hand.  The new 5 is VERY light, but doesn't feel cheap, but I'm not sure how I like the feel of it.  I have on

  • NAT and Servers behind CSS 11501

    All, Please forgive my asking this question again. I was injured shortly after asking the last time and out of work for a long period of time. My problem stems from needing to allow my web servers to initiate traffic to the outside world from behind

  • My phone says searching.. i cant call or anything whats going on

    can i get some help.. my iphone says searching...i have no signal.. what is going on .

  • Drag and Drop in Flash ?

    I cannot seem to get the script correct? Can anyone let me knwo if it is the script that incorrect or the naming etc of my movieclips.. basically I want several of the movie clip pegs to be able to be dragged and dropped and snap to the targets...i w