Using static methods to instantiate an object

Hi,
I have a class A which has a static method which instantiates it. If I were to instantiate the class A twice with it's static method within class B then you would think class B would have two instances of class A, right?
Example:
class A
   static int i = 0;
   public A(int _i)
       i = _i;
   public static A newA(int _i)
        return new A(_i);
class B
    public B()
        A.newA(5);
        A.newA(3);
        System.out.println(A.i);
    public static void main(String[] args)
        B b = new B();
}Is there really two instances of class A or just one? I think it would be the same one because if you check the int i it would be 3 and not 5. Maybe static instantiated objects have the same reference within the JVM as long as you don't reference them yourself?
-Bruce

It
seems like you are the only one having trouble
understanding the question.Well I was only trying to help. If you don't want any help, its up to you, but if that's the case then I fail to see why you bothered posting in the first place...?
Allow me to point out the confusing points in your posts:
you would think class B would have two
instances of class A, right?The above makes no sense. What do you mean by one class "having" instances of another class? Perhaps you mean that class B holds two static references to instances of Class A, but in your code that is not the case. Can you explain what you mean by this?
Is there really two instances of class
A or just one?You have created two instances.
>I think it would be the same one because if you
check the int i it would be 3 and not 5.
I fail to see what that has to do with the number of instances that have been created...?
Maybe static instantiated objects have the
same reference within the JVM as long as you
don't reference them yourself????? What is a "static instantiated object"? If you mean that it was created via some call to a static method, then how is it different to creating an object inside the main method, or any other method that was called by main? (i.e. any method)
What do you mean by "the same reference within the JVM"? The same as what?
What happened to the first call "A.newA(5)"?
I think it was overidden by the second call
"A.newA(3)".As i already asked, what do you mean by this?
If you change the line for the constructor
in A to i = i * i you will get "9" as the
output, if you delete the call "A.newA(3)"
you will get "25" as the output. Yes. What part of this is cauing a problem?

Similar Messages

  • Why not to use static methods - with example

    Hi Everyone,
    I'd like to continue the below thread about "why not to use static methods"
    Why not to use static methods
    with a concrete example.
    In my small application I need to be able to send keystrokes. (java.awt.Robot class is used for this)
    I created the following class for these "operations" with static methods:
    public class KeyboardInput {
         private static Robot r;
         static {
              try {
                   r = new Robot();
              } catch (AWTException e) {
                   throw new RuntimeException(e + "Robot couldn't be initialized.");
         public static void wait(int millis){
              r.delay(millis);
         public static void copy() {
              r.keyPress(KeyEvent.VK_CONTROL);
              r.keyPress(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_CONTROL);
         public static void altTab() {
              r.keyPress(KeyEvent.VK_ALT);
              r.keyPress(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_ALT);
                   // more methods like  paste(), tab(), shiftTab(), rightArrow()
    }Do you thinks it is a good solution? How could it be improved? I've seen something about Singleton vs. static methods somewhere. Would it be better to use Singleton?
    Thanks for any comments in advance,
    lemonboston

    maheshguruswamy wrote:
    lemonboston wrote:
    maheshguruswamy wrote:
    I think a singleton might be a better approach for you. Just kill the public constructor and provide a getInstance method to provide lazy initialization.Thanks maheshguruswamy for advising on the steps to create a singleton from this class.
    Could you maybe advise also about why do you say that it would be better to use singleton? What's behind it? Thanks!In short, it seems to me that a single instance of your class will be able to coordinate actions across your entire application. So a singleton should be enough.But that doesn't answer why he should prefer a singleton instead over a bunch of static methods. Functionally the two are almost identical. In both cases there's only one "thing" on which to call methods--either a single instance of the class, or the class itself.
    To answer the question, the main reason to use a Singleton over a classful of static methods is the same reason the drives a lot of non-static vs. static decisions: Polymorphism.
    If you use a Singleton (and and interface), you can do something like this:
    KeyboardInput kbi = get_some_instance_of_some_class_that_implements_KeyboardInput_somehow_maybe_from_a_factory();And then whatever is calling KBI's public methods only has to know that it has an implementor of that interface, without caring which concrete class it is, and you can substitute whatever implementation is appropriate in a given context. If you don't need to do that, then the static method approach is probably sufficient.
    There are other reasons that may suggest a Singleton--serialization, persistence, use as a JavaBean pop to mind--but they're less common and less compelling in my experience.
    And finally, if this thing maintains any state between method calls, although you can handle that with static member variables, it's more in keeping with the OO paradigm to make them non-static fields of an instance of that class.

  • Why not to use static methods in interfaces?

    why?

    Because static methods are always attached to a particular class -- not an object. So object polymorphism (which is what interfaces are good for) won't help. Now, what you can do is say that subclasses must implement a method that looks an awful lot like a static method, in that it doesn't depend on object state.
    This bugged me, and it still bugs me a little bit in that I have to instantiate an object of a type in order to call these pseudo-static methods. When the pseudo-static methods tell the user how to initialize the object, you get a bit of a chicken-and-egg problem.

  • GUI component services: Use static methods or query direct parent?

    Hi
    I have a large panel (covers most of the window) that contains a square grid of smaller panels. Each smaller panel contains a square grid of buttons. For instance, PnlGrid contains a few PnlGridSections and each PnlGridSection contains some BtnGrids.
    There is certain funtionality that must be available to BtnGrid objects but I am not sure if I should simply provide static methods in PnlGrid and access them from everywhere else in the code or have BtnGrid ask its direct parent (i.e. PnlGridSection) to deal with it.
    For instance, I am currently using a static method, PnlGrid.getIconCache(), to retrieve a reference to the icon cache and locate the texture I need from within a BtnGrid. Would it more correct to retrieve a pointer to the direct parent of this button (i.e. PnlGridSection) and have him return the pointer to the icon cache?
    Thanks

    Hi
    I have a large panel (covers most of the window) that contains a square grid of smaller panels. Each smaller panel contains a square grid of buttons. For instance, PnlGrid contains a few PnlGridSections and each PnlGridSection contains some BtnGrids.
    There is certain funtionality that must be available to BtnGrid objects but I am not sure if I should simply provide static methods in PnlGrid and access them from everywhere else in the code or have BtnGrid ask its direct parent (i.e. PnlGridSection) to deal with it.
    For instance, I am currently using a static method, PnlGrid.getIconCache(), to retrieve a reference to the icon cache and locate the texture I need from within a BtnGrid. Would it more correct to retrieve a pointer to the direct parent of this button (i.e. PnlGridSection) and have him return the pointer to the icon cache?
    Thanks

  • Best practice for using static methods

    When i want to call a static method, should i call:
    1) classInstance.staticMethod()
    or should i call
    2) ClassName.staticMethod()??
    is the first style bad programming practice?

    dubwai: which compiler?I had assumed that this was what the JLS specifies, but intsead, it goes into length how to make the runtime environment treat calls to static methods on instances as if they were static calls on the variable's type.
    However, I imagine anyone creating a compiler would go ahead and compile calls to static methods on instances to static calls on the variable's type instead of going through the effort of making the runtime environment treat calls to static methods on instances as if they were static calls on the variable's type.
    But of course, it is concievable that somone didn't in their compiler. I doubt it but it is possible. Sun does compile calls to static methods on instances to static calls on the variable's type:
    public class Garbage
        public static void main(String[] args)
            Garbage g = null;
            method();
            g.method();
        public static void method()
            System.out.println("method");
    public class playground.Garbage extends java.lang.Object {
        public playground.Garbage();
        public static void main(java.lang.String[]);
        public static void method();
    Method playground.Garbage()
       0 aload_0
       1 invokespecial #1 <Method java.lang.Object()>
       4 return
    Method void main(java.lang.String[])
       0 aconst_null
       1 astore_1
       2 invokestatic #3 <Method void method()>
       5 invokestatic #3 <Method void method()>
       8 return
    Method void method()
       0 getstatic #4 <Field java.io.PrintStream out>
       3 ldc #5 <String "method">
       5 invokevirtual #6 <Method void println(java.lang.String)>
       8 return

  • Using static methods in JavaBeans

    Hi:
    I am creating several beans as part of my application. Is it ok, to make all of them static (no global variables are used) and access in JSP's and Servlets as XXBean.method(var1, var 1). Is this a problem ? (vs creating a new XXBean and using it in every page/servlet).
    I have gut feeling that static methods are better and give better memory usage and performance - as oppose in other scenario I am creating a new Bean for every page access - could not verify. and not sure not creating (new Bean) would give any problems.
    Thanks for sharing.

    I think you mixed up JavaBeans and Enterprise JavaBeans (EJBs) ...
    I think Sun Microsystems really named them badly ...
    They are in fact totally different things ...
    I agree with them.
    Please read the tutorials first.
    Asuka Kenji (UserID = 289)
    (Duke Dollar Hunting now ...)

  • NEED HELP WITH USING STATIC METHOD - PLEASE RESPOND ASAP!

    I am trying to set a value on a class using a static method. I have defined a servlet attribute (let's call it myAttribute) on my webserver. I have a serlvet (let's call it myServlet) that has an init() method. I have modified this init() method to retrieve the attribute value (myAttribute). I need to make this attribute value accessible in another class (let's call it myOtherClass), so my question revolves around not knowing how to set this attribute value on my other class using a static method (let's call it setMyStuff()). I want to be able to make a call to the static method setMyStuff() with the value of my servlet attribute. I dont know enough about static member variables and methods. I need to know what to do in my init() method. I need to know what else I need to do in myServlet and also what all I need in the other class as well. I feel like a lot of my problems revolve around not knowing the proper syntax as well.
    Please reply soon!!! Thanks in advance.

    class a
    private static String aa = "";
    public static setVar (String var)
    aa = var;
    class b
    public void init()
    a.aa = "try";
    public static void main(String b[])
    b myB = new b ();
    b.init();
    hope this help;
    bye _drag                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to use the method getParameterValues() of request object in JSP?

    I'm trying to use the method
    String a[]=request.getParameterValues("ch_box");
    to retrieve the values from the form
    but it gives the error
    "Method getParamaterValues(java.lang.String) not found in interface javax.servlet.http.HttpServletRequest."
    so plz tell me how to overcome this hurdle?
    thanx

    Well, just one note... either you have a typo in your code, or else in your post.
    If you cut and pasted the error message (which it looks like you did), then the method getParamaterValues() should be getParameterValues() instead (notice the spelling difference), so you probably just have a typo in your code.

  • Virtual ESA appliance update and upgrade using static method

    What are the static servers for updates and upgrading if you are using a virtual appliance ?
    I know that the if you use a standard appliance they are:
    downloads-static.ironport.com: 208.90.58.105 on port 80
    update-manifests.ironport.com: 208.90.58.5 on port 443
    updates-static.ironport.com: 208.90.58.25 on port 80
    But I see that my virtual appliance is trying to go to "update-manifests.sco.cisco.com"   - are there other differences for the virtual appliance ?

    Yes, I can confirm through my own experiences over the past week that the Virtual Appliances do not use the same update servers.
    Virtual Appliances point to dynamichost update-manifests.sco.cisco.com - 208.90.58.6. I'm not sure about the static update IPs, as the static sub domains do not seem to exist on the sco.cisco.com and it looks like Cisco is using Akamai CDN to distribute updates over port 80. You may need to allow iyour Virtual ESAs out on port 80 any, and 443 seems to be a single host.
    Also I found the following article most helpful for Virtual ESA Updates:
    http://www.cisco.com/c/en/us/support/docs/security/email-security-appliance/118065-maintainandoperate-esa-00.html

  • Using static methods.

    Hi,
    I have few class variables like socket, and boolean datatypes in a class.
    This class is intantiated in lot of place and everytime the new instance is created the variables are re-initialized to their original values.
    I dont want variables values to change everytime an instance is created. So should i declare them static? if i do so is there any precaution or cautions i should look out for?
    Thank you.

    Thank for the reply here is the code.
    public class ServerComm{
    //class variables.
              private  boolean connValid = false;
          private  Socket  cvwSock;
          //Open the connection to the CVW server.
         public void openConnection() {
              try {
                   cvwSock = new Socket(InetAddress.getByName(host), iport);
                   boolean isConnect = cvwSock.isConnected();
                   System.out.println("ServerComm,openconnection2:got socket conn: "
                             + cvwSock);
                   connValid = true;
              catch (Exception v) {
                   connValid = false;
                        System.out
                                  .println("servercomm,openconnection3:You are trying to connect to CVW server with name: "
                                            + host + " Unknown CVW Server");
                   else
                        v.printStackTrace();
                   System.exit(1);
                   return;
          * Sends a command to the CVW server if the connection is valid.
         public void sendCmdToServer(String cmd) {
    //connection valid become false  with new instance of class so returns
                    if (!connValid)
                   return;
              if (idleState) {
                   idleState = false;
              ByteArrayOutputStream bs = new ByteArrayOutputStream();
              PrintStream ps = new PrintStream(bs);
              ps.println(cmd);
              ps.flush();
              // opening a streams to send message to cvw server
              try {
    //cvwsock is initialized to null with new instance of class
                   cvwSock.getOutputStream().write(bs.toByteArray());
                   cvwSock.getOutputStream().flush();
    catch (Exception v) {
                   System.out.println("ServerComm: Error opening Stream: " + v);
    //Anothe class
    public class SomeClass{
    ServerComm server= new ServerComm()//creating instance of the above class
    //some expressions
    server.sendCmdToServer(command); //connValid in ServerComm is initialized to false again. to doesnt send command but returns
    }.In the above code in SomeClass when intantiated the connValid variable is reinitialized to false and hence it returns when called server.sendCmdToServer(command). while the openConnection() is succesfull called from another class

  • JUNIT : how to call static methods through mock objects.

    Hi,
    I am writing unit test cases for an action class. The method which i want to test calls one static method of a helper class. Though I create mock of that helper class, but I am not able to call the static methods through the mock object as the methods are static. So the control of my test case goes to that static method and again that static method calls two or more different static methods. So by this I am testing the entire flow instead of testing the unit of code of the action class. So it can't be called as unit test ?
    Can any one suggest me that how can I call static methods through mock objects.

    The OP's problem is that the object under test calls a static method of a helper class, for which he wants to provide a mock class
    Hence, he must break the code under test to call the mock class instead of the regular helper class (because static methods are not polymorphic)
    that wouldn't have happened if this helper class had been coded to interfaces rather than static methods
    instead of :
    public class Helper() {
        public static void getSomeHelp();
    public class MockHelper() {
        public static void getSomeHelp();
    }do :
    public class ClassUnderTest {
        private Helper helper;
        public void methodUnderTest() {  // unchanged
            helper.getSomeHelp();
    public interface Helper {
        public void getSomeHelp();
    public class HelperImpl implements Helper {
        public void getSomeHelp() {
            // actual implementation
    public class MockHelper implements Helper {
        public void getSomeHelp() {
            // mock implementation
    }

  • Static method decisions

    Dear all experts,
    I have got some problems understanding when to use static methods or passing the classes through constructor.
    I have got a class which needs to be accessed by several classes and also the classes inside the classes etc....
    Instead of passing classes around, should I just create a single static class which can be accessed by all the classes without needing to instantiate the class?
    I found that, i particularly in doubt when there are classes like "TableParser", "PropertiesReader" etc which some classes deep down in the hierarchy need access to those classes...
    Also, making the class static would it decrease the security of the whole program?? Say if i have got an encrytion class which does all the encrypt and decrypt, if i let it be static, isn't it easier to let people accessing the method? the same applies to properties editor etc??
    Any help would be really appreciated.
    Thx

    thx again jverd... (remember the security question? :)
    )I remember your id, but I didn't recall which thread(s) I had seen it in.
    >
    based on the understanding of what you said, do you
    mean that, if i am only using a class to store or read
    a setting file, it's ok to let it static? (so that all
    classes can access it whenever they like without
    passing the parser class to classes?)Um, again, you're terminology's a little off, so I'm not sure exactly what you mean, and even the description "store or read a seting file" could have a couple of interpretations.
    For example....You read the file once, and the config data it constains is accessible throughout your app and never changes. This might be a candidate for a class that only had static methods, but it would be kind of inflexible. What if later some other part of your app, or some other library that you develop that your app is going to use, wants to get its configuration from a file. In that case, I might want to have a couple instances of that class around. One for the global config that reads one file, and another for the config for that library that might read another file.
    I'd probably not even think about it as "reading a settings file." Rather, I'd see that as two parts: providing config settings to the app via a class, and reading a file to populate that class. The settings would exist independent of the fact that you can populate them from a file.
    I'd think about how I want to use them and decide whether to instantiate the class or use static methods based on that. Separately, I'd think about how this class or an instance of it is gonna get popuated with data from outside the program.
    I might decide to have different instances hold different sets of config data, and therefore use instance (non-static) methods to access the data in each of those instances, but I might register the instances--say by name, or maybe just in a list--and I could use a static method to acess the map or list: Config dbConfig = Config.getConfig("database"); Also, I wouldn't generally make a decsision on whether to use class methods or instance methods based on not having to pass a parameter.
    If you're thinking "I'd like to use static because it's easier. Can I get away with it here," then you're viewing objects as a burden to be avoided, which kind of defeats the purpose of using OO techniques in the first place.

  • Is Using Static functions advisable from performance(speed) point of view

    I was wondering if using a static function would be slower than using a normal function, especially when the function is to be accessed by multiple threads since the same memory area is used each time the static function is accessed from any of the threads. Thus is it right if I say that static functions are not suitable for multiThreaded access ?

    I was wondering if using a static function would be
    slower than using a normal function,Static functions are linked at compile time, while normal functions have to be linked based on the runtime type of the object they are called on. This lookup means that static function invocations are likely to be faster.
    especially when
    the function is to be accessed by multiple threads
    since the same memory area is used each time the
    static function is accessed from any of the threads.If you are talking about the code segment, where the function definition is held, there is only a single copy of each "normal" function as well. The code segment is also read-only, so there are no issues with multiple threads reading and executing the same code at the same time.
    There are the normal issues with multi-threaded access to variables in static functions that exist with normal functions.
    Thus is it right if I say that static functions are
    not suitable for multiThreaded access ?Static functions are no safer than non-static functions in terms of thread safety. On the other hand, it is no more dangerous having multiple threads calling a static function than having multiple threads calling a non-static function on the same object. Exactly the same thread safety techniques apply whether you are working in a static or a non-static context.
    With the above in mind, there is a great deal of design difference between static functions and non-static functions. They mean very different things when creating a system, and an operation that is suited for a static function is very likely not appropriate in a non-static context, and vice versa. The important thing is to make sure the design is appropriate for what the system is trying to do.
    The most common use of static functions is for object creation... The Factory design pattern uses static methods to create objects of a given type, the Singleton design pattern uses static methods to allow access to itself.

  • Static methods. Why?

    I understand what static means, and that each class has only ONE copy of its static variables and methods.
    I an see the benefits of using static variables, but i cant seem to get my head round the benefits of using static methods.
    What is the advantage of this, and is there a common situation where they are appropriate? (not main)
    Cheers

    I don't think static exists to prevent namespace conflicts. I think that the reason for static to exist is just as I described it: When you've got some task that is appropriate to be performed by a specific class, but that doesn't make sense to be associated with a particular instance of that class.
    For example, String.valueOf. It's appropriate for the String class to have a method that returns the String representation of anything you feed to it (so it's in the String class) but it doesn't make sense for that method to be associated with a particular instance of String (so it's static). After all, you don't yet have a String to operate on--you're producing the String.
    Which raises another interesting point: I wonder what the design decision was that led to
    String.valueOf(int)
    String.valueOf(long)
    String.valueOf(Object)
    etc.
    instead of
    new String(int)
    new String(long)
    newString(Object)
    etc.
    I've used both patterns in my own work, but I don't really have any good criteria for picking one over the other.
    One thing that comes to mind for the general case is that with the static method, you can return a subclass, which you can't do with a constructor. Conversely, with a constructor, the caller knows exactly which class he'll get, whereas with a static method he doesn't. Of course, these points don't apply to String, as it's final.
    I'm new to java, but as far as I can tell, "static"
    means "global". The reason for having them in classes
    is mainly to prevent name conflicts. For instance,
    you could have an Array object, and a List object, and
    both could have sort() methods, but they may be very
    different types of methods. By forcing sort() to be a
    member of a class, instead of a global identifier, you
    have Array.sort() and List.sort(), which is much
    safer.
    It seems that the java designers went to great lengths
    to make sure there are no namespace conflicts in the
    language. Maybe they even went a bit too far in this
    sometimes.

  • Non-static method error message

    why this error message? i'm new to Java.
    Non-static method compare(java.lang.object,java.lang.Object) cannot be referenced from a static context at line 54.
    Any assistance would be greatly appreciated. Thanks.
    Calling Method;
    private static void selectionSort(Object[] objectArray)
    int min, temp;
    for (int index = 0; index < objectArray.length-1; index++)
    min = index;
    int alen = objectArray.length;
    for (int scan = index+1; scan < alen; scan++)
    (Line 54) NameComparator.compare(objectArray[scan],objectArray[min]);
    Invoked Class/Method:
    import java.util.Comparator;
    public class NameComparator implements Comparator {
    private String object, object1, firstCompare, secondCompare;
    // Constructors
    public NameComparator()
    firstCompare = object;
    secondCompare = object1;
    // Compare method
    public int compare(Object object, Object object1)
    int result = firstCompare.compareTo(secondCompare);
    return result;
    }

    That message occurs when you attempt to call a regular class method from a static class method, which usually means that you've called a regular method from main(). Remember this is main:
    public static void main( String[] args ) { . . . }The static keyword means that main() is part of the class, but not part of objects created from that class. The error message is really saying:
    // You're trying to use a method that needs an object of this class type,
    // but you don't have an object of this class type.I get this message often enough. It just means that I forgot to create an object, or that I forgot to use it when I called the method.
    class SomeThing {
      public static void main( String[] args {
        doWhatever(); // wrong - requires a SomeThing object
        SomeThing st = new SomeThing(); // got a SomeThing now
        doWhatever(); // still wrong - only works for an object
        st.doWhatever(); // finally right!
      } // end main()
      SomeThing() { . . . } // constructor for SomeThings
      doWhatever() { . . . } // method that a SomeThing can perform
    } // end of class SomeThing

Maybe you are looking for

  • BPEL demo Deploying to Server in VirtualBox  Appliance

    I have just installed the "Oracle SOA Suite/BPM Suite VirtualBox Appliance". I have created a very simple BPEL process (the typical Hello John) in Jdev and now I'm trying to deploy it to this server. I have not changed any configuration in the applia

  • G4 Cube & ViewSonic LCD TV ?

    I have a 450MHz Cube that i would like to hook up to this TV http://www.viewsonic.com/products/lcdtv/NX2232w/#specs Do i have to upgrade the video card to this? http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&rd=1&item=280171012505&ssPageName= STRK:MEW

  • Best way to extract XML value wiith an xpath

    Hello, I wonder what is the best way to extract text value from XmlType with an xpath. I need to insert a row inside a table where the row's data come from xpath extractions of an XmlType. I do a lot of (approximative 20) : EXTRACTVALUE(var.myxmltype

  • Problem un-installing ECC 6.0 on Redhat EL 4 / MaxDB

    Hi, After encountering a few problems with my installation I decided to run an un-install using sapinst. I enter the passwords for the Database System Administrator and Database Manager Operator and click next but sapinst just hangs. The bottom of th

  • How to export Android sms to Mac?

    I want to be able to export my Android SMS database to my Mac in a friendly txt, html or pdf format that is easy to read. I have the sms.db file ready to use, i just want to be able to easily convert it. What applications that are completely free can