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

Similar Messages

  • Excessive use of 'static' in Objects

    Hello all,
    I have inherited a code base which consists of around 90 objects seemingly randomly thrown together in a down and dirty effort to crank out working code as soon as possible. The original programmer has left the company and I've inherited his projects. While attempting to isolate some performance shortcomings I noticed that nearly every single class has a static method of some sort or another. My understanding is that this is clearly a bad idea as, if for no other reason, those objects, having a static method, will exist during the entire lifetime of the application and are not candidates to be GC'd. Furthermore these objects contain many String instances which, if the object that contains them isn't ever eliminated, will remain as huge memory hogs as well.
    So, in essence, what are the general thoughts of the architects and developers on this board regarding the use of the 'static' keyword and it's effect on Object design and the implications for performance and memory? Any feedback would be greatly appreciated. I have looked through numerous books on OO design but nobody seems to speak directly to the implications and "best practices" of designing with the 'static' keyword, where, when and how it's most effectively used, etc.
    Thanks!

    Hi,
    would you consider that the primary motivation for use of static, that the method in question use only class member variables?Often yes, but not always. The example given by jschell above is typical of a static method, but you can't always make methods static like this. If isDefined(String s) were specified by an interface (it couldn't be private in this case though), to implement different variants of what it means for a String to be 'defined', then you couldn't make the method static even if it did not depend on the object you are calling it on.
    However I am still looking for a good "rule of thumb" that will help me to determine what the most appropriate use of the static keyword is/should be.For methods you should ask yourself "How will the method be called?" If it only makes sense to call it on an instance of the object then DON'T make it static, even if it could be. Static methods should only be called like this:
       ClassName.staticMethod();and not like this:
       instanceOfClass.staticMethod();as this second style of invocation is very misleading (and it really winds me up when I see it!).
    As for fields - in my own code I tend to have private static final objects for constants or 'collections' that are used by many instances, or which are available through public static utility methods. Immutable static final fields I often make public. Pretty much everything else is non-static. I have no idea whether this is 'best practice' though.
    You may also want to look at the java.util.Collections and java.util.Arrays classes. These cannot be instantiated and provide only static utility methods for manipulating other objects. It can sometimes help to split off the static 'utility' functions into another class like this, especially if common functions can be applied to an interface.
    Ol.

  • Static final String

    Any body know hat this following code means?
    public static final String JAVA_HOME = System.getProperty("java.home");
    public static final String CURRENT_DIR = System.getProperty("user.dir");
    thanks you

    It defines two object variables (JAVA_HOME and CURRENT_DIR), that are:
    static - there's only ever one of them, no matter how many times the class they are in is instantiated.
    final - cannot be changed.
    public - available to all other classes outside of the current class.
    The two variables are then assigned to system properties, for a list of system properties and their meanings look here:
    http://java.sun.com/docs/books/tutorial/essential/system/properties.html
    A 'static final' variable is called a 'constant'. It is very useful when you want to define a variable and keep it that way. For example, if you wrote a program that worked out the area of a circle, you might want a static final variable PI = 3.14159.
    Constant variables are usually defined in uppercase. This is not forced, but it's good practice.

  • 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.

  • Public static final Comparator String CASE_INSENSITIVE_ORDER

    in this declaration..
    public static final Comparator<String> CASE_INSENSITIVE_ORDER
    what does <String> mean?
    thanks!

    what does the Comparator do. Look at the API and you would see the following description about the compare method.
    public int compare(Object o1,
    Object o2)Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
    The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)
    The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
    Finally, the implementer must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.
    It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals."
    Now your question is about what <String> is in your declaration. It is the type of the objects which are going to be compared.

  • Static final problem.

    I am having one large java card application. Because of its size I splited it in three packages. One applet package and two library packages.
    In one class that is part of one library package I am having several constants which are byte arrays. When I put the identifier static final, I was able to build the project but when I was running the applet, I was getting the exception 0x6F00 when I access that field in a static way. What can be the reason for that? When I modify these fields in a way that I remove the static final identifier and when I accessed that field in a instance manner, everything was ok.

    Hi,
    VCheck the JCVM spec for limitations on library packages. Since static fields (objects) are created in the context of the applet that first uses the class other applets in different packages would get a security exception when using these fields as they are in a different context. One solution is to initialise the constants in the applet and pass a reference to the class in the library package. This is not as clean but it works. Just be sure to clear the references when you uninstall the applet to allow the JCRE to remove your applet instances.
    Cheers,
    Shane

  • Static final

    I need to share several objects among all instances, so I mark them as static. As far as these variables should be initialized only once they must be final as well. The problem is that I can't use static initializer, because these final static objects are constructed by 2nd class.
    class Y {
         private static final var1;
         private static final var2;
         Y() {}
         static void useVars() { ... }
         void useVars() { ... }
    class Main {
         public static void main(String[] args) {
              v1 = getVar1();
              v2 = getVar2();
              initClassY(v1, v2); // initializing static final vars for Y
    }

    You can use blank finals. This allows one to declare
    a final without initializing it.This is correct.
    The catch is you must initialize it before you use it.This is true, but not exact.
    Actually, you must initialize it in the constructor
    The following will not compile :
    public MyClass{
       final int BLANK_FINAL;
       public MyClass(int arg1){
          setBF(arg1);
       private void setBF(int arg1){
          BLANK_FINAL = arg1 * 200 + 86; //compiler error

  • Static final bug tools?

    Looking for a tool that can detect this:
    static final int[] FOO = {1,2,3,4}
    FOO[3] = 99;
    So basically something that can look through the jar or class files and see if a final reference is being dereferenced and has that being used as an lvalue. Not that that case is always going to be a bug, but if a tool could print out where that occured it would make it way easier to track down the cases that are. Is there any such tool?

    well guess i was wrong, i thought u couldnt compile
    something that tries to asign a value to a static
    final variableYou cannot, but that is not what's happening in that example. That code modifies the object referred to by a final variable, which is permitted. What's not allowed is to reassign null or a different reference to the variable. It's the variable that's final, not the object.

  • Enum vs static final String

    I was going to use static final Strings as enumerated constants in my application, but would like to see if I should be using enums instead.
    In terms of efficiency, if I have, say, 5 enumerated elements, will only one copy of the enumerated element be in memory, like a static final String? So regardless of how many times I refer to it, all references point to the same instance (I'm not sure if what I just said even makes sense in the context of enums, but perhaps you could clarify).
    Are there any reasons why for enumerated constants that are known at development time, why static final Strings (or static final anything, for that matter) should be used instead of enums if you're using JDK 1.5?
    Thanks.

    In terms of efficiency, if I have, say, 5 enumerated elements, will only one copy of
    the enumerated element be in memory, like a static final String?I don't know if it addesses your concerns, but the the Java Language Specification says this about enums: "It is a compile-time error to attempt to explicitly instantiate an enum type (�15.9.1). The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants." (http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9)
    As for the problems of memory usage, how big are these strings anyway?
    The advantages of using enums over static final strings are discussed in the "technotes" accompanying 1.5 http://java.sun.com/javase/6/docs/technotes/guides/language/enums.html They list the following as problems with the static final "antipattern"
      * It is not typesafe (methods that expect one of your constants can be sent any old string)
      * There is no name space - so you must continually be sure that your constants don't have names that may be confused
      * Brittleness. Your strings will be compiled into the clients that use them. Then later you add a new constant...
    �  * Printed values will be uninformative. Perhaps less of a problem for Strings, but, still, simply printing the string will leave its semantic significance obscure.

  • Static final in (Class or Interface)

    Hello Friends ,
    What is the difference in having a public static final variable in an class and having the same kind of
    declarations in an Interface ?
    Does the interface is better or having it in a class ?
    Thanks in Advance,
    -S

    shyamnambiar wrote:
    But I'm not clear . you mean to say its all the same .It does not make any difference ?The only difference that it makes (and that might be an important difference) is what you communicate with your design an intention.
    Constants should usually be placed within their context since that's where they are going to be used, and that's where developers will look. It's more common to place the constants in the class that they are related to. They should not be placed in an empty final class just because you want to group constants. You should also avoid placing constants in an interface just because you then can implement that interface to "get hold of" the constants.
    Kaj

  • Threaded Queries from Single static Connection object - Good approach?

    Hi,
    I need to generate a report where I need to query count(1) from over one hundred tables from oracle 10g database. I am not updating or deleting any record.
    My approach is to use a single static connection object and create one thread for each table and capture the result back into a static hashtable.
    But still, I am not getting any substantial performance improvement. Earlier, my report took 40 minutes, when it was non-threaded and now it takes 30 minutes.
    Is there anything more I can do to make my report get the counts faster? Will a connection pool help?

    Tolls wrote:
    jschell wrote:
    I was told by the DBA that count(1) works faster than count(*)....that's why....Unlikely. Certainly not true in current versions of Oracle if that is the source.Not unlikely, actually not true. Beneath the hood Oracle turns a count(1) into a count(*) in order to deal with this. Why? Because count(1) is turned into count(*) in order to avoid it being slower (Oracle 7 was the last time count(1) was different). And the reason generally given is because so many people were mistakenly using count(1) thinking it performed better that they decided to put in the "conversion" to fix the silly queries.
    I think this it the [Ask Tom|http://asktom.oracle.com/pls/asktom/f?p=100:11:109792721681931::::P11_QUESTION_ID:1156159920245] link I used last time this came up here.
    I knew all that, but I missed that the OP had specified the database vendor and version.

  • Declaring public static final variables in jsp?

    The question is in the title...
    I know this is not a jsp forum, but some people here might know if it's possible or not.
    If yes, how to declare them and how to access them from other jsp pages?
    Thx

    If you need that, you definitely do too much work in your JSPs. You should do all your work in Servlets (or Actions if you're using Struts or something similar).
    Your JSPs should only do the presentation.
    Remember that JSPs are not classes (they are compiled into classes internally, but you don't have direct access to those).
    If you absolutely need such a public static final field that you want to access from several JSPs, just define it in a Class and reference that class from your JSPs.

  • ERROR: serializable class HelloComponent does not declare a static final

    Hi everyone! I'm sorry but I'm a newbie to Java and I'm having some, I assume, basic problems learning to compile and run with javac. Here is my code:
    import javax.swing.* ;
    import java.awt.* ;
    public class MyJava {
    * @param args
    public static void main(String[] args)
    // TODO Auto-generated method stub
    JFrame frame = new JFrame( "HelloJava" ) ;
    HelloComponent hello = new HelloComponent() ;
    frame.add( hello ) ;
    frame.setSize( 300, 300 ) ;
    frame.setVisible( true ) ;
    class HelloComponent extends JComponent
    public void paintComponent( Graphics g )
    g.drawString( "Hello Java it's me!", 125, 95 ) ;
    And here is the error:
    1. WARNING in HelloJava.java
    (at line 20)
    class HelloComponent extends JComponent {
    ^^^^^^^^^^^^^^
    The serializable class HelloComponent does not declare a static final serialVersionUID field of type long
    ANY HELP WOULD BE GREAT! THANKS! =)

    Every time I extend GameLoop, it gives me the warning
    serializable class X does not declare a static final serialVersionUID field of type long
    This is just a warning. You do not need to fix this because the class you are writing will never be serialized by the gaming engine. If you really want the warning to go away, add the code to your class:
    static final long serialVersionUID=0;

  • Trying to acces the value of a public static final int using reflection

    -Java 6
    -Windows XP
    -Signed Applet
    doing the following:
    Class.forName(classname).getField(code).getInt(null);
    is giving me the error:
    java.lang.IllegalAccessException: Class com.cc.applet.util.ServiceConfiguration can not access a member of class com.cc.util.error.codes.SendMessageErrorCodes with modifiers "public static final"
         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.getInt(Unknown Source)
    I'm not understanding why it can't access the value of the field. Any help would be great.
    Edited by: zparticle on Oct 17, 2007 11:07 PM

    stefan.schulz wrote:
    oebert, you are right. Good one.
    I actually think that, in this case, the message is misleading. The current implementation of sun.reflect.Reflection.ensureMemberAccess() treats any failing access check the same. It should and could inculde better contextual information.Stefan,
    That is a good point. Did you file a RFE with Sun yet? I also think they should provide a more contextual error message in this case.
    Gili

  • Constant values (public static final String) are not shown??

    This has already been posted and no body answered. Any help is appreciated.
    In web service is it possible to expose the Constants used in the application. Let say for my web service I need to pass value for Operation, possible values for this are (add, delete, update). Is it possible expose these constant values(add, delete, update) visible to client application accesssing the web service.
    Server Side:
    public static final String ADD = "ADDOPP";
    public static final String DELETE = "DELETEOPP";
    public static final String UPDATE = "UPDATEOPP";
    client Side: mywebserviceport.setOperation( mywebservicePort.ADD );
    thanks
    vijay

    Sure, you can use JAX-WS and enums.
    For example on the server:
    @WebService
    public class echo {
    public enum Status {RED, YELLOW, GREEN}
    @WebMethod
    public Status echoStatus(Status status) {
    return status;
    on the client you get.
    @WebService(name = "Echo", wsdlLocation ="..." )
    public interface Echo {
    @WebMethod
    public Status echoStatus(
    @WebParam(name = "arg0", targetNamespace = "")
    Status arg0);
    @XmlEnum
    public enum Status {
    GREEN,
    RED,
    YELLOW;
    public String value() {
    return name();
    public static Status fromValue(String v) {
    return valueOf(v);
    }

Maybe you are looking for