Static object vs non-static object......

What is the purpose of static object????
is there any example showing that the advantage of declaring a static object rather than a non-static object??
secondly, why static object/primitive data is initialized before non-static object/primitive data?
apreciate for any respond

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class Test3 extends JFrame {
  JDesktopPane jdp = new JDesktopPane();
  public Test3() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = getContentPane();
    content.add(jdp, BorderLayout.CENTER);
    JButton jb = new JButton("New Thingy");
    content.add(jb, BorderLayout.SOUTH);
    jb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        try { jdp.add(new Thingy(jdp.getWidth(), jdp.getHeight())); }
        catch (Exception e) { System.out.println(e.getMessage()); }
    setSize(300, 300);
    setVisible(true);
  public static void main(String[] args) { new Test3(); }
class Thingy extends JInternalFrame {
  Random r = new Random();
  static int count=0; //  HERE IT IS!!!
  public Thingy(int w, int h) throws Exception {
    if (count==6) throw new Exception("Too Many Thingies");
    setTitle("T-"+(++count));
    setBounds(r.nextInt(w-100),r.nextInt(h-50),100,50);
    setVisible(true);
}

Similar Messages

  • Static variable and non-static

    I have a quick question. The following syntax compiles.
    private String t = key;
    private static String key = "key";
    But this doesn't compile.
    private String t = key;
    private String key = "key";
    Can anybody explain how it is treated in java compiler?
    Thanks.

    jverd wrote:
    doremifasollatido wrote:
    I understand that completely. I didn't say that the OP's version with static didn't work. I was just giving an alternative to show that you don't need static, if you change the order that the instance variables are declared.My problem with the underlined is that, while technically true, I can see where a newbie would take it as "oh, so that's how I can get rid of static," and focus only on how to satisfy the compiler, rather than on learning a) when it's appropriate to make something static or not from a design perspective, and b) what the implications of that decision are, for both static and non.
    I have just a wee bit of a prejudice against the "what do I type to make the error messages go away" approach. :-)That sounds good to me. We're currently trying to fix an issue caused by the fact that one class has most of its variables as static, when they should really be instance variables. There should only be one active instance of this class at a time, but the values of the static variables stick around when you call "new ThisClass()". So, old data interferes with new data, and various errors happen. The class has many static methods to access the static variables, but it should have been more of a Singleton--an actual object with non-static variables. The active instance of the Singleton would need to be replaced at logout/login (as opposed to shutdown completely and restart the JVM), but then at least when the new instance were created, then all of the variables would be initialized to empty--the old instance would disappear. The solution at the moment (solution by others--I don't agree) is to clear each static Vector and then set the reference to null (setting to null would be enough to drop the old data, but certain people don't get that...). This is fragile because many variables were missed in this "cleanup" process, and it will be easy to forget to "cleanup" new variables in the future. This class has been misdesigned for years (much longer than I've been here). The calls to static methods permeate the application, so it isn't easy to fix it quickly. There are several of these misdesigned classes in our application--a mix of static and non-static, when nothing or almost nothing should be static.

  • Mime Objects and non-static template

    Hi All,
    When I bring up a non-static web template, icons stored as mime objects are not initially displayed.  When I do a drill down or any other operation these are then displayed. 
    I know that this is not an issue with static layouts.
    Does anyone know how to force it so that these are displayed when the template is first called up?
    Cheers,
    Robert Zovic
    Arinso International

    Sorry Max,
    I originally included this in this group, although it is a web template designed using the Web Application Design tool.
    The template itself has had it's property set to non static.  This is to overcome issues with the connection/resources remaining locked by the ICM.
    The icons have been uploaded through se80.  It's strange but on the initial callup of the template they don't appear.  On each subsequent access, they do.
    Robert

  • Example of Serialized objects and non-Serialized objects

    Hi,
    Can you please tell me some of eample of Serialized objects and nonserialized objects in java and j2ee.
    Thanks
    alex.

    sravan123 wrote:
    Serialised objects are File ,all Collection classes , subclasses of Throwable and subclasses of Number.
    Non-Serialised objects are Connection,DataSourrce,Resultset , Thread and MathYou forgot to log in as another user before answering your own question incorrectly for reasons I'm currently unable to fathom

  • How to create Entity object for Non Database Object.

    Friends,
    I have a requirement something like, I will be getting some huge amount of data from external system via CORBA, I have to display the data in jsff page in <af:table>. My requirement is If User updates any of the row I need to identify what are all the rows user updated and Need to invoke again a CORBA call for only UPDATED Rows.
    Basically here, I am not dealing anything with the Database, I assume using Entity we can find out a status of the row whether the row is updated/deleted/created .
    How can I create an Entity object in this case.
    Any help will be highly appreciated !!!
    Thanks

    The basics steps are described here http://download.oracle.com/docs/cd/E14571_01/web.1111/b31974/bcadveo.htm#sm0328
    and here http://download.oracle.com/docs/cd/E14571_01/web.1111/b31974/bcadvvo.htm#sm0341
    You need to change the underlying data source from pl/sql to meet your requirements (CORBA).
    Timo

  • Static method or non-static method

    hi,
    i was wondering would making a method static gain any efficiency (in J2ME)- obviously the method wont use any instance variables / methods.
    thanks.

    Guess what? It depends...
    You may think of implementing a Singleton pattern (see Gamma, GoF...) that goes like this:
    public class MySingleton {
        private static MySingleton instance;
        // constructor
        private MySingleton() {
        // getInstance method
        public static MySingleton getInstance() {
            if(instance == null)
                instance = new MySingleton();
            return instance;
        // further code
    }This pattern makes sure you will only have one instance of that class. See also the "WorkFlow Application Example: DeliveryMIDlet" from the NOKIA Forum. (http://www.microjava.com/articles/techtalk/workflow)

  • "non-static variable cannot be referenced from a static contex"

    Hi, i'm writing a booking program at school and i'm getting 27 "non-static variable cannot be referenced from a static contex" errors. I can't find anything wrong with the code so I'm just asking you guys to look it through..
    public class bokningsmeny
    Bokning[] bokningslista = new Bokning[1000];
    String fornamn;
    String efternamn;
    String civilstand;
    String adress;
    String personnr;
    String telefonnr;
    int regnr;
    double inkomst;
    public static void main(String[] args)
    for(;;)
    System.out.println("\nMeny");
    System.out.println("________\n");
    System.out.println("1. Mata in nya personer.");
    System.out.println("2. S&ouml;k personen via personnummer och skriv personens andra uppgifter.");
    System.out.println("3. S&ouml;k personen via efternamn och skriv personens andra uppgifter.");
    System.out.println("4. S&ouml;k personen via personnummer och &auml;ndra adress.");
    System.out.println("5. S&ouml;k personen via personnummer och &auml;ndra telefonnummer.");
    System.out.println("6. S&ouml;k personen via personnummer och &auml;ndra civilst&aring;nd.");
    System.out.println("7. S&ouml;k personen vis personnummer och &auml;ndra inkomst");
    System.out.println("8. Skriv ut alla personer med givet namn.");
    System.out.println("9. Skriv ut alla personer med givet efternamn");
    System.out.println("10. Skriv ut alla personer med given adress");
    System.out.println("11. Skriv ut hela listan");
    System.out.println("12. Avsluta\n");
    int menyval = Keyboard.readInt();
    System.out.println("\n");
    switch(menyval)
    case 1:
    System.out.println("Mata in nya personer.\n______________________\n");
    boolean BOOuppgifter = false;
    for(int i = 0; i <= 1000; i++)
    if(bokningslista +== null)+
    +{+
    +SkrivInUppgifter();+
    +System.out.println("\nSt&auml;mmer informationen? (Y/N)");+
    +boolean BOOcase1yesorno = IsInputCorrect();+
    +if(BOOcase1yesorno == true)+
    +{+
    +System.out.println("\nBokningen lyckades!\n");+
    +bokningslista += new Bokning(fornamn, efternamn, civilstand, adress, personnr, telefonnr, regnr, inkomst);
    ++++else if(BOOcase1yesorno == false
    ++++System.out.println("\nBokningen avbruten.\n")
    ++++break
    ++++++break
    ++++case 2
    ++++System.out.println("Sok person med personnummer och &auml;ndra uppgifter.")
    ++System.out.println("___________________________________________________________\n")
    ++System.out.print("Skriv in sokord: ")
    ++String query = Keyboard.readString()
    ++query = query.toUpperCase()
    ++String personnummersok
    ++boolean contains
    ++int antal = 0
    ++boolean BOOcase2result = false
    ++System.out.println("Resultat: \n_________\n")
    ++for(int i = 0; i < 1000; i++
    ++++if(bokningslista +!<b<br />+<em<b<br />+++personnummersok = (bokningslista+.hamtaPersonnum()).t
    ++++contains = personnummersok.con
    ++++if(cont
    +<<br />++++BOOcase2r
    ++++ant
    ++++fornamn = bokningslist
    +++++efternamn = boknin
    ++++++personnr
    +++++++System.out.println(antal + ". " + fornam
    ++++<e<br />+++++++System.out.pri<br<br />+++++<em<br />+++++++System.out.println("\nVilket sokresultat vill du v&bdquo
    ++++<<br />+++++++if(case2ch
    +++++++System.ou
    +++<e<<br />+++<em<br />++++
    ++<em<br />+++++++System.out.p
    +++++<e<br />+++<<br<br /<br />+++++++System.out.printl
    +++<em<br />+++++<em<br />++
    <e<br />++++++++Sy
    +++++
    ++++++<e<br /><em<br />++++++++<<br />+++++<e<br />+++
    +++<<br />+++++++++else if(case11exit != 'y' &<br<br />+<<br />++++
    ++++
    +++++
    ++++<e<br />+++++++
    ++++<em<br />+++++
    +++<em<br />+++++<em<br />++++<<br />++++++
    ++++<e<br />+++++++<e<br />++<em<br />++++<e<br />+++<<br />+++++++++System.out.println("\n\nNamn: " + fornamn + "
    ++++++++++ "\nHemadress: " + adr
    ++++++++++ telefon
    +<<br />+++++++++Syste
    ++++<em<br />+++++++++if(correct
    <em<br />++<em<br />++<<br />++++<e<br /><<<br /><e<br />+++++++++I have another file with the Bokning.java class in it but I know for sure that its error free. Notice that I'm not nearly done with the program, theres like 10 more 'cases' to be created but I dont w
    ++<em</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Your code goes "+" crazy there, but here is your problem:
    public class B extends A {
        public void method() {}
        public static void main(String[] args) {
            //method(); //non-static method method() cannot be referenced from a static context
            B b = new B();
            b.method();
    }You need to be clear about the difference between static methods and non-static (instance) methods. Instance methods are applied to objects.

  • Non-static method getContentPane() cannot be referenced from a static conte

    From this line I'm getting an error
    Container bmC = getContentPane();
    - non-static method getContentPane() cannot be referenced from a static context
    Aprecciate solution,
    thx

    The reason this is happening is that you can't call non-static methods from a static method. Non-static methods need an instance in order to be called. Static methods are not associated with an instance.

  • SRM non transportable objects

    Hi,
    I have a request from our SRM Consultant to change the below objects to non-transportable objects.  I would like to know the best process in handling this.  It is not clear to me as to what objects these are.  Some of them are tables, as I found out later.  But other objects are not clear.
    BBP_WS_VC - Define external call services.  Used for definition of catalogue call structures.   
    q       BBP_BACKEND_DEST - Definition of backend systems  
    q       BBP_DET_LOGSYS - Define backend system for product category 
    q       BBP_TARGET_OBJ  - Determine target object in backend system  
    q       BBP_DET_ACCT - Define G/L Account for product category and account assignment category.
    q       BBPV_SRC_DET
    q       BBPV_AVL_DET  - Sourcing by Vendor List flag.   
    q       TWPURLSVR - Logical web servers for logical systems   
    q       Any R3TR SICF objects, which contain user names
    q       Any R3TR SMIM objects, typically images for the catalogue
    thanks in advance,
    Abdul

    Hi
    This is not recommended and best practice by SAP.
    Any specific reasons - why you want to do this ?
    Please consult the same with SAP by creating a OSS message as well.
    Regards
    - Atul

  • Static calling non-static

    What is the best way aroung a static main method trying to call a non static method?

    Fixing the design of the program, IMHO. This kind of a
    think does not happen in a poperly designed program.Exactly. IF a static method needs to access a non-static variable, it needs to specify which instance of its class owns the variable.
    public static void main(Sting EAGLES[]))
       MyJDialog  mjd = new MyJDialog();
       mjd.setSomeParameter(true);
    }Here's the Reader's Digest Condensed Version&#169; of the rules (with grammatical license):
    1. A static method may only access the static data of it's class, not non-static data.
    2. static methods can only call static methods, not non-static.
    3. There ain't no this in static methods.
    4. You can't override a static method to be non-static.

  • Non-static method/object cannot be referenced from a static context...?????

    What does this mean. I know about static, but I don't understand why I get this so many times.
    I try to do something pretty normal and this is what I get a lot of times. I mean: the main() method should be static right? Then what good is the main() method if you cannot let it do stuff for you like this:
    public class Test extends JFrame
        public Test
            setSize( 100, 100 );
            show();
    public static main( String args[] )
        Test window = new Test();
        draw();
    public void draw()
        blablabla whatever I want to do, a lot of times I can't.....
    }Why is this, what is the reason for Java to forbid this and what can I do about it?

    Your draw() method, since it isn't defined as static is considered by Java to be part of your Test object; hence, it can only be invoked in the context of an existing instance of your object. In other words, any Java program that wanted to use your draw() method would have to create an instance of your Test class using something likemyTest = new Test()Your main method, however, is something different. Since you want to execute your class as a program, the Java run-time environment needs to have standard starting point. This starting point is the main method. The problem is that the main method must be static, because the run-time environment cannot be expected to know beforehand the correct way to create an instance of your class so that non-static methods can be invoked. The drawback is that your main method can only directly access methods that are defined as static.
    There are two possible solutions to this problem, and which of the two you want to use depends on the object-oriented nature of your program.
    On the one hand, if your draw() method is closely tied to the object itself, if the draw() method is actually drawing your object or a part of it, it should be left as an instance method, and you should simpy use the instance of the object you created in your main method:public static main( String args[] )
        Test window = new Test();
        // maybe some code to generate something to draw???
        window.draw();
    }This is what I think you are trying to do.
    On the other hand, if your draw() method was some kind of universal method that didn't depend in any way on the current configuration of your instance, you could simply define draw() as static at which point your main method (or a method in an external class) could invoke it directly, without a corresponding instance. But if you did that, the draw() method itself would only be able to access static variables and methods.
    Doug

  • Single object referenced by static method

    Hi,
    I have a class, that I know in advance will only be instantiated ONE time. My problem is that I wish to address this object from elsewhere in the programme. I'm using:
    class Client{
    private static Client me = new Client();
    public static Client getMe(){
         return me;
    ....lots of non-static methods
    Is there a better way of doing this (of course there is, but what??)

    Wouldn't have a clue what GoF is, but yes, what you are describing is an honest-to-god, taught to students, pattern.
    It is the accepted way of doing this, you aren't being dodgy (at least not yet).
    Good luck,
    Radish21

  • Static fields in serialized Vector objects

    just a curious question:
    If I have a Vector filled with Objects of all the same type, and the Object contains a static field, and I then Serialize the Vector, will it still give better performance than if the field wasn't static? Thanks,
    Max

    nevermind - found out the hard way that static fields won't get Serialized

  • Pass an object from a static method

    Hi,
    I'm trying to pass a reference to an object from a static method, but I get an error when compiling.
    Say for example I have this:
    public class obj1 {
    public void myMethod (int i, Object ob, etc...) {
    ...and I want to call this method from a method that looks like this:
    public class obj2 {
    public static int anotherMethod(...) {
    obj1.myMethod(1,this,...);
    ...Can I pass a reference from obj2 to obj1 any other way?
    Thanks alot.

    how can I get a reference to obj2 then?Pay no attention to zdude's answer - it's nonsense.
    You're confused about basic Java concepts. obj2 is a class, not an object. References point to objects, not classes. There is no obj2 object in the code you show, so you cannot have a reference to an obj2 object.
    Maybe if you post some more code, we can get an idea of what you're trying to do. You might want to try the New to Java forum.

  • Calling a non-static method from another Class

    Hello forum experts:
    Please excuse me for my poor Java vocabulary. I am a newbie and requesting for help. So please bear with me! I am listing below the program flow to enable the experts understand the problem and guide me towards a solution.
    1. ClassA instantiates ClassB to create an object instance, say ObjB1 that
        populates a JTable.
    2. User selects a row in the table and then clicks a button on the icon toolbar
        which is part of UIMenu class.
    3. This user action is to invoke a method UpdateDatabase() of object ObjB1. Now I want to call this method from UIMenu class.
    (a). I could create a new instance ObjB2 of ClassB and call UpdateDatabase(),
                                      == OR ==
    (b). I could declare UpdateDatabase() as static and call this method without
         creating a new instance of ClassB.With option (a), I will be looking at two different object instances.The UpdateDatabase() method manipulates
    object specific data.
    With option (b), if I declare the method as static, the variables used in the method would also have to be static.
    The variables, in which case, would not be object specific.
    Is there a way or technique in Java that will allow me to reference the UpdateDatabase() method of the existing
    object ObjB1 without requiring me to use static variables? In other words, call non-static methods in a static
    way?
    Any ideas or thoughts will be of tremendous help. Thanks in advance.

    Hello Forum:
    Danny_From_Tower, Encephalatic: Thank you both for your responses.
    Here is what I have done so far. I have a button called "btnAccept" created in the class MyMenu.
    and declared as public.
    public class MyMenu {
        public JButton btnAccept;
         //Constructor
         public MyMenu()     {
              btnAccept = new JButton("Accept");
    }     I instantiate an object for MyMenu class in the main application class MyApp.
    public class MyApp {
         private     MyMenu menu;
         //Constructor     
         public MyApp(){
              menu = new MyMenu();     
         public void openOrder(){
               MyGUI MyIntFrame = new MyGUI(menu.btnAccept);          
    }I pass this button all the way down to the class detail02. Now I want to set up a listener for this
    button in the class detail02. I am not able to do this.
    public class MyGUI {
         private JButton acceptButton;
         private detail02 dtl1 = new detail02(acceptButton);
         //Constructor
         public AppGUI(JButton iButton){
         acceptButton = iButton;
    public class detail02{
        private JButton acceptButton;
        //Constructor
        public detail02(JButton iButton){
          acceptButton = iButton;
          acceptButton.addActionListener(new acceptListener());               
       //method
        private void acceptListener_actionPerformed(ActionEvent e){
           System.out.println("Menu item [" + e.getActionCommand(  ) + "] was pressed.");
        class acceptListener implements ActionListener {       
            public void actionPerformed(ActionEvent e) {
                   acceptListener_actionPerformed(e);
    }  I am not able to get the button Listener to work. I get NullPointerException at this line
              acceptButton.addActionListener(new acceptListener());in the class detail02.
    Is this the right way? Or is there a better way of accomplishing my objective?
    Please help. Your inputs are precious! Thank you very much for your time!

Maybe you are looking for

  • My Brand New Refurbished Ipod Touch is not working

    I just bought a brand new refurbished Ipod touch 32GB (current generation), after a week it shows flickering white screens. I seldom used it for the whole week. When I went to apple service centre they told me that the water leak indicator turns into

  • How to start up when hard drive is toast?

    I've got the sick iMac of a friend at home. The hard disk on his intel based iMac (2008) crashed completely. I can start up the computer using my OS install CD (SL), but when I go to Disk Utiliy there's no hard disk there. Only the DVD drive, which d

  • Lumia 920 Memory Full error message when trying to...

    Anyone come across this issue Thanks Paul O'Davies

  • Wrong ownership on TM-- is it safe to 'sudo chown -R user Time-Machine ?

    I ran Migration Assistant by a new user "Admin" to recover the accounts of 3 users on Lion. After the migration, Admin owns the Time Machine history of one of the users (even though account Admin didn't even exist at the time these backups were made)

  • Ways to find out userexits.

    Hi frineds, Yesterday i had a interview, In this interview one of the interviewr asked me a question. In how many ways  we can find out an exit ? I said 2 ways but he said, no we can find out this exit in 6 ways. Can any one explain me in how many wa