Usage of non static members in a static class

Can you explain the usage of nonstatic members in a static class?

Skydev2u wrote:
I just recently started learning Java so I probably know less than you do. But from what I've learned so far a static class is a class that you can only have one instance of, like the main method. As far as non static members in a static class I think it allows the user to modify some content of the class(variables) even though the class is static. A quick Google help should help though.Actually the idea behind a static class is that you dont have any instances of it at all, its more of a place holder for things that dont have anywhere to live.
Non-static members in a static class wouldnt have much use

Similar Messages

  • Main accessing non static members

    How can main access non static members itself being static?

    Why would you want to?
    Main has one purpose and one purpose only, it is there for kicking off a program and ensuring it closes cleanly. I know they generally don't teach this early on in programming classes, but in my opinion they should.
    You should never ever be doing any data processing in main. In some cases you may need to set data in main, like for example if the class the main is in is part of a larger project but you want to be able to test the class stand-alone without having to run the rest of the project. But in most cases main should do nothing with any data save the args, which should usually just be passed along.
    The reason behind this is simple, soon enough you will be writing programmes that span multiple class objects, only the main of the class you use to kick it off ever gets touched, so any data processing that is in the other classes main methods, never happens.
    Why you should learn how to get out of main now is, you may want to use the class you are writting now as part of a future project. But again you have the problem of unless this class is the one that kicks that project off, any processing in main does not happen. Plus what happens if you want to process the data in you are processing in main somewhere else? Code re-use of code in main is a no go.
    Plus, by getting out of main you no longer have to worry about that whole static/ non-static issue.
    JSG
    Sorry, this is just one of my pet-peeves

  • Your Opinions: Inner Classes Need static Members

    Hi All,
    I want to solicit opinions for a minor change to the way inner classes work. I submitted this as an RFE to Sun and they rejected it, really without giving a reason. I'd like to know your opinions. If there is strong support I will repost the RFE.
    As you probably know, inner classes cannot have static members. The following generates a compiler error:import java.util.*;
    public class MyClass {
       class MyInnerClass {
          // Next line causes compiler error...
          static Map m = new HashMap();
    }In order to get around this you have to make the Map variable a static member of the containing class:import java.util.*;
    public class MyClass {
       static Map m = new HashMap(); // so much for encapsulation...
       class MyInnerClass {
    }I am suggesting that inner class be allowed to contain static members. Here's my reasoning...please comment:
    There are times when members (i.e., fields and methods) rightfully belong to the class as a whole, not to any particular instance of a class. I'm sure we've all found times when it was necessary to have static members in our classes. The same issues that necessitated using static members in top-level classes make them desirable for inner classes as well.
    Designing a class as an inner class is a step toward encapsulation. By forcing static members that logically belong in an inner class to be declared in the containing class is to crack the encapsulation, IMHO.
    Even though a containing class has access to all of an inner class' members (including private members) and vice versa, I think the notion of inner static members still is more OO-ish.
    What are your opinions? Would allowing inner classes to contain static members make Java more object oriented? I think it would.
    Technically, I don't think there's any reason this cannot work since the JVM has no notion of inner classes, per se.
    What do you think?

    an inner class is effectively a non static instance
    variable of its enclosing class. Instance member, but not a variable. it's a class, a type, not a variable.
    >
    I think the problem here is that making a field static
    means more than just that that field and its value are
    common to every instance of the class. It means that
    the value is valid without an instantiation of that
    class.
    Since the class itself must be instantiated (it is
    not static), What do you mean, excatly, by "_must_ be instantiated"? You are not ever "required" to instantiate anything unless you want to use it.
    you can't have static member data inside it. I don't see how this follows from the previous part of the statement.
    How would you reference the static member data of
    the inner class? You would have to specify an
    instance of the inner class, and since this breaks
    the meaning of static, you can't have static members
    in an inner class.How about outerObj.InnerClass.staticMember The syntax is well defined. The question at hand is, do we really want to allow this? The syntax to do this should only be an issue after that question has been answered in the affirmative. The people at Sun have decided not to allow it, so for now, syntax is a non-issue.
    >
    if you wanted a static member in an inner class you
    could put it in a super class of the inner class...Or in the enclosing class, as suggested in the orginal post.

  • Factory class and static members

    I don't understand very well why sometimes you can find a factory class (for example for the xml parsers). What's its aim?
    And why sometuimes, instead of a constructor, some classes have only static methods that returns a reference to that object?
    Anyone can tell me?
    Thanks

    Static memebers can be used in places where instances of its enclosing class is not neccesary.Only a method is required to be executed. Let me tell you with an example,
    class ConnectionPool {
    public static giveConnection(int index) {
    In the above example, our objective is to use only the method public static giveConnection(int index) {} , and not any of the other attributes of this class. You have 2 ways to use this method : One is, you can instantiate ConnectionPool p = new ConnectionPool(); . Second is , just use ConnectionPool.giveConnection(2);
    The first solution may create instance and obstruct your performance. Seond one does not do that. All invokers of this method do not instantiate and occupy space.
    Usually, factory classes have static members. Because these classes are used as a supporting processing factory. Theses members can be considered as utility methods. Hence static property will better suit for them. This answer will also tell you that the use of constructors here is not neccessary.
    Hope this has helped you.
    Rajesh

  • Static vs Non--Static members

    I'm having some trouble trying to understand the differences between static and non-static members.
    I've read a few online information about static members, but I don't understand the purpose of static members.
    Can someone try to explain the main points of static members and the differences between static and non-static members?

    I'm having some trouble trying to understand the
    differences between static and non-static members.
    I've read a few online information about static
    members, but I don't understand the purpose of static
    members.
    Can someone try to explain the main points of static
    members and the differences between static and
    non-static members?Static means only one per class. If you have a Class and generate 20 objects of this class or more, they all share the same copies of any static variables. This is as opposed to instance variables of which each Object has its own. If an object changes one of its instance variables, this doesn't affect another object's instance variables.
    Having said this, however, vague and general questions are great if you are face to face with a tutor where you can have a conversation but are very difficult to answer in this format. Your best bet is to go through several online articles (and there are many good ones, just google for them) and then coming back with specific questions. Another option is to go through a book or two. Most have a chapter covering this.
    Message was edited by:
    petes1234

  • Static block in superclass to initialize static members in subclasses

    I am trying to create several classes that are all very similar and should derive from a super class because they all have common members and are all initialized the same way. I would prefer every member of my subclasses to be static and final as they will be initialized once and only once. I can not figure out the best way to make this work. Here is an example (using code that does not work, but you can see what I am trying to do):
    class Super
        protected static final String initializedInEachSubclass;
        protected static final String alsoInitializedInEachSubclass;
        // these need to be accessed from anywhere
        public static final String initializedInSuperclass;
        public static final String alsoInitializedInSuperclass;
        // this static initialization block is exactly the same for every instance
        static
            // initialize these based on what the subclasses initialized
            initializedInSuperclass = initializedInEachSubclass + alsoInitializedInEachSubclass;
        private Super () {} // never instantiated
        public static final String getMoreInfo ()
            // the same for each instance
            return Integer.toString (initializedInEachSubclass.length ());
    class Sub1 extends Super
        static
            initializedInEachSubclass = "My String for Sub1";
            alsoInitializedInEachSubclass = "My Other String for Sub1";
        private Sub1 () {} // never instantiated
    }The problem with the above code is that the static block in Super uses static final variables that have not been initialized yet. I can't make Super abstract. If I initialize the final variables in Super, then I can not reinitialize them in Sub1. But if they are not final, then they could be changed after being initialized (which I would rather not allow). I could make everything protected and not final and then make public get... () methods, but I like accessing them as attributes. It seems like this should be possible, but everything I have tried has led me to a catch-22.
    Any ideas on how I can put all my redundant initialization code in one place but still allow the subclasses to initialize the static members that make each of them unique? I will be happy to clarify my examples if you need more information.
    Edited by: sawatdee on Jan 3, 2008 9:04 AM

    sawatdee wrote:
    I am basically trying to avoid having redundant code in several classes when the code will be exactly the same in all of them.That's the wrong reason to subclass. You subclass to express type specialization. That is, a Dog IS-A Mammal, but it's a special type of Mammal that implements certain common mammal behaviors in a dog-specific way. A LinkedList IS-A List, but in implements common list operations in linked-list-specific ways.
    I don't really need to have the static final members in a superclass (and I don't even need a superclass at all), but I don't know how else to execute a big static initialization block in several classes when that code is exactly the same in all of them. Without knowing more details about what you're trying to do, this sounds like a case for composition rather than inheritance. What's now your superclass would be a separate class that all your "sublasses" have a reference to. If they each need their own values for its attributes, they'd each have their own instances, and the stuff that's static in the current superclass would be non-static in the "subs". If the values for the common attributes are class-wide across the "subs", the contained former super can be static.
    public class CommonAttrs {
      private final String attr1;
      private final int attr2;
      public CommonAttrs(String attr1, int attr2) {
        this.attr1 = attr1;
        this.attr2 = attr2;
    public class FormerSub1 {
      private static final CommonAttrs = new CommonAttrs("abc", 123);
    ... etc. ..

  • Inheritance of static members

    I realise that this is a very basic question but I'm hoping that someone will explain the answer to me. I have two classes, one extends the other and both have instance variables assigning a name to the object when it is instantiated. The superclass also has a print method which displays the name of the object. When the superclass and subclass are tested, both print their own names. However, if I make the name variables static, as well as the print function in the superclass, when I call printName on both superclass and subclass, both print the name of the superclass. Why? I had understood that static members were inherited in the same way as instance members.
    public class MySuper{
         protected static String myName = "Super";
         protected static void printName(){
              System.out.println(myName);
    public class MySub extends MySuper{
         protected static String myName = "Sub";
    }MySuper.printName(); prints "Super"
    MySub.printName(); prints "Super"

    A static method uses static variables of the class
    itself unless otherwise specified.So why doesn't MySub use it's own variables?
    It does; the problem is that there are two variables with the same name. By default it is the variable of the class where the method is declared in, so MySub.printName() uses the variable MySuper.myName. Declaring a new variable in the subclass, static or not, does not override or replace the variable in the superclass, it simply hides it from the methods of the subclass.
    When you inherit a method, it is not copied intothe SubClass, it is only available to be
    used from this SubClass.
    That was what I was trying to imply. That the
    printName method is inherited by MySub and is
    available to be used by MySub.
    So MySub can use printName() (from MySuper) and
    executes this on it's own variable myName="Sub".
    No, it uses the superclass variable; subclass variables don't replace superclass ones.
    Why
    is that not happening with my static example when
    that's exactly what happens with my non-static
    example? Where is the difference?
    There is no difference; you will see the same thing happen with instance methods:class MySuper {
        String myName = "Super";
        void printName() {
           System.out.println(myName);
    class MySub {
        String myName = "Sub";
    }When you call printName for an object of class MySub, you'll see "Super" printed.

  • Calling non-static command from within static method

    Hello,
    I have a static method that reads bytes from serial port, and I want to set a jTextField from within this method. but I get error that says it is not possible to call non static method from a static one. How can it be solved?

    ashkan.ekhtiari wrote:
    No, MTTjTextField is the name of jTextFiled class instance.You haven't declared any such variable in the class you posted, not to mention that such a variable name violates standard code conventions.
    This is and instance of that object actually. You haven't declared any such variable in the class you posted.
    the problem is something else. No, it isn't, based on the information you have provided. If you want accurate guidance, don't post misleading information about your problem.
    It can not be set from within static method.A question commonly asked on Java forums concerns an error message similar to the following:
    non-static variable cannot be referenced from a static context
    In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term instance is often substituted for non-static, as in "instance method" or "instance variable."
    The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    Once you understand this concept, you can fix your own problem.
    ~

  • Singleton with static members only

    If I have a singleton class with static members only and I'd like to ensure that nobody accidentally instantiates the class, would it make sense to declare the class abstract? Or instead should I leave it non-abstract but make the no-argument constructor private? Or both?
    Which of these approaches would you recommend?
    Thanks.

    pros of using classical singletons (per Head First
    Design Patterns):
    1) It ensures that one and only one object is
    instantiated for a given class.This is effectively the same as using a non-instantiable class with all static members. You don't have an instance, but you have exactly one of it.
    2) It gives a global point of access like a global
    variableAgain, same thing with a non-instantiable class with all static members.
    3) It is only created when you need it (unlike a
    global variable) and thus wastes no resources if it
    is not needed.Again, same thing.
    Also, Java does not have global variables.
    Also, no variable in Java requires more than 8 bytes, and most are 4 or 2.
    4) Using a static self-contained class in place of a
    singleton can be a source of subtle, hard-to-find
    bugs often involving order of initialization of
    static code.Eh? Example please?
    5) Global variables encourage developers to pollute
    the namespace with lots of global references to small
    objects.What global variable? Java doesn't have global variables? How is a class full of statics any more a global than a "real" singleton?

  • Sharing static members between Swing application and Web application

    Hi,
    if someone has done this please help:
    I have created 3 classes:
    Mainclass using JFrame which is used as host class for DBConnectionManager class,
    and ConfigBean class used for storing static configuration parameters:
         static public String strUser = "";
    static public String strPassword = "";
    static public String strDB = "";
    static public int nMaxConn = 0;
    static public String strPoolName = "";
    static public boolean bConnected = false;
    static public int nCurrentUsers = 0;
    static public DBConnectionManager manager = null;
         public DBConnectionManager getDBManager()
    return this.manager;
    public void setDBManager(DBConnectionManager manager)
    this.manager = manager;
    DBConnectionManager class uses static instance to see if this is only class created by client users.
    Only static member in this class is getInstance member function for startig manager:
         static synchronized public DBConnectionManager getInstance()
    if (instance == null)
    instance = new DBConnectionManager();
    return instance;
    In Mainclass I also created non static DBConnectionManager class for manipluation with host administrator.
    Then I created web application layout in Tomcat 4 and used index.jsp:
    <%@ page import="java.sql.*,java.io.*" %>
    <jsp:useBean id="cfgbean" class="webvobapli.ConfigBean" scope="application" />
    <%!
    webvobapli.DBConnectionManager db = null;
    String strMessage = "";
    Statement stmt1;
    ResultSet rset1;
    String strQuery = "select count(*) from cards";
    %>
    <html>
    <%
         try
              db = cfgbean.getDBManager();
              if(db==null)
                   strMessage = "Error";
              else
                   Connection con = db.getConnection("central2");
                   if(con != null)
                        stmt1 = con.createStatement();
                        rset1 = stmt1.executeQuery(strQuery);
                        rset1.next();
                        strMessage = rset1.getString(1);
                   else
                        strMessage = "NULL";
         catch(Exception e)
              strMessage = e.toString();
    %>
    <p>Message = <%=strMessage%></p>
    </html>
    Question: why db = cfgbean.getDBManager(); returns null if I created instance of DBConnectionManager
    class in Mainclass and assigned it to ConfigBean as static instance before running web application.
    Shouldn't all java programs share static memory area?
    Beast Regards
    Branislav Cavlin

    Question: why db = cfgbean.getDBManager(); returns null if I created >>instance of DBConnectionManager
    class in Mainclass and assigned it to ConfigBean as static instance >>before running web application.
    Shouldn't all java programs share static memory area?You say you create the db objects BEFORE you run the web application - now I could be misunderstanding what you are saying, but does this not involve two JVM's (one to create initial db objects, which then exits, then second JVM fires you app server/servlet container) - which would explain why a null object is being returned.

  • Using a non-static vector in a generic class with static methods

    I have a little problem with a class (the code is shown underneath). The problem is the Assign method. This method should return a clone (an exact copy) of the set given as an argument. When making a new instance of a GenericSet (with the Initialize method) within the Assign method, the variables of the original set and the clone have both a reference to the same vector, while there exists two instances of GenericSet. My question is how to refer the clone GenericSet's argument to a new vector instead of the existing vector of the original GenericSet. I hope you can help me. Thanks
    package genericset;
    import java.util.*;
    public class GenericSet<E>{
    private Vector v;
    public GenericSet(Vector vec) {
    v = vec;
    private <T extends Comparable> Item<T> get(int index) {
    return (Item<T>) v.get(index);
    public static <T extends Comparable> GenericSet<T> initialize() {
    return new GenericSet<T>(new Vector());
    public Vector getVector() {
    return v;
    public static <T extends Comparable> GenericSet<T> insert (GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (!member(g,i))
    v.addElement(i);
    return g;
    public static <T extends Comparable> GenericSet<T> delete(GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (member(g,i))
    v.remove(i);
    return g;
    public static <T extends Comparable> boolean member(GenericSet<T> z, Item<T> i) {
    Vector v = z.getVector();
    return v.contains(i);
    public static <T extends Comparable> boolean equal(GenericSet<T> z1, GenericSet<T> z2) {
    Vector v1 = z1.getVector();
    Vector v2 = z2.getVector();
    if((v1 == null) && (v2 != null))
    return false;
    return v1.equals(v2);
    public static <T extends Comparable> boolean empty(GenericSet<T> z) {
    return (cardinality(z) == 0);
    public static <T extends Comparable> GenericSet<T> union(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = assign(z1);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> intersection(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> difference(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    insert(g, elem);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(!member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> assign(GenericSet<T> z) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z); i++) {
    Item<T> elem = z.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> boolean subset(GenericSet<T> z1, GenericSet<T> z2) {
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    return false;
    return true;
    public static <T extends Comparable> int cardinality(GenericSet<T> z){
    Vector v = z.getVector();
    return v.size();
    }

    The issue is not "reference a non-static interface", but simply that you cannot reference a non-static field in a static method - what value of the field ed would the static method use? Seems to me your findEditorData should look something like this:   public static EditorBean findEditorData( String username, EditorBean editorData )
          return editorData.ed.findEditor( username );
       }

  • Life and memory space for static members of a class

    hi,
    as we all know that instance members reside on heap inside object to which they belong, where do the static members reside on the heap or on stack..

    All objects reside on the heap.*
    *I think Java 6 or 7 may allow purely local objects to live on the stack, but if an object is referred to by a member variable--whether static or not--it will live on the heap.                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Do sub classes get their own copy of base class static members?

    Hi,
    I am sub classing a certain classwhich has a static member boolean used for status updating. I have two sub classes, each needing its own static copy of the boolean. Do they get their own copy, or must I redeclare the member in each sub class?
    AC

    You must re-declare them (hiding the superclass member) if you wish the subclass members to be "independent".
    class Coin {
        public static int FOO;
        public static int BAR;
    class Coin2 extends Coin {
        public static int BAR = 2;
        public static void main(String[] args) {
            FOO = 1;
            System.out.println("Coin FOO  = " + Coin.FOO);  // 1
            System.out.println("Coin2 FOO = " + Coin2.FOO); // 1
            System.out.println("Coin BAR  = " + Coin.BAR);  // 0
            System.out.println("Coin2 BAR = " + Coin2.BAR); // 2
    }HTH! :o)

  • JVM and static members of classes

    Hello Experts,
    I have applet project. Recently I reorganized the code and I made so many class members "static".
    The applet starts from javascript link from browser. When I start it at first time, everythink is OK,
    but when I start it second time there is a problem with these static members(Actually they are dialogs,
    panels, vectors and s.o.) They are saved in the memory in some way. When I close the parent browser(the browser
    that holds the javascript link) and then start again, everything is OK, because I starting applet for
    first time.
    How can I make the following calls like the first one ?
    Please help me !
    Best Regards,
    Valeri

    When u are opening a browser the static variables
    are persistance unless u closed the window.
    so while u are opening the second time the
    static variables are not initalizing.
    so if u remove the static .
    Or after displaying the applet u initialize the
    staic variable.

  • Static members & the lifespan of a midlet's memory?

    consider a midlet with the following simplified code:
    static Image img;
    startApp()
      if (img == null)
        img = Image.createImage("foo.gif");
      else
        print("IMAGE IS ALREADY IN MEMORY, NO NEED TO RELOAD IT");
    }on sun & sony erricson midp2 emulators, the 2nd time this midlet is started: the image is already in memory, i assume because of the use of "static".
    but then, does it mean that when exiting a midlets, static members are always kept alive?
    for how long?
    which kind of memory is used? (heap i assume...)
    what about other midlets: will they suffer from much-less-of-available-heap for running?

    This does not happen on the phones, do not count on it.

Maybe you are looking for