Unsure of purpose of static methods

Hello,
I know the distinction between instance and class variables, but the same distinction in terms of methods is giving me a bit of confusion.
With variables, it makes sense that common (class) variables are not copied for each instance, while instance variables are. I'm able to see the implications and purpose of separating instance and class in this case.
I'm having trouble figuring out the purpose of instance versus class methods, though. Here, there is no 'copy' of the method to be made, right, so what are the benefits of having instance vs class methods?
So far I know instance methods cannot be used unless an instance exists, and I think(?) the only limitation of class methods is that they be used from where their access modifier allows?
Can anybody please shed some light on what the purpose of having both types of methods is, and maybe some other theory on it? The online tutorials I read on this matter weren't very clear for me? Thank you.

An instance of an object has state. This Person object's state is that the name is "John Smith" and the age is 25. That other Person object's state is that the name is "Mary Jones" and the age is 17.
If you have a canDrink() method, you have to have state--the Person's age--to use for executing that method, so you need an instance to call it on.
john.canDrink() uses the state of that object to return true.
mary.canDrink() uses the state of that object to return false.
Static methods are related to the class as a whole, not to the state of any particular instance of that class.
For example, Person.howManyPersonObjectsHaveBeenCreated()

Similar Messages

  • What is the purpose of Static methods inside a class?

    Hi,
    What is the purpose of Static methods inside a class?
    I want the answers apart from "A static method does not require instance of class(to access) and it can directly be accessed by the class name itself"
    My question is what is the exact purpose of a static method ?
    Unlike attributes, a separate copy of instance attributes will be created for each instance of a class where as only one copy of static attributes will be created for all instances.
    Will a separate copy of instance method be created for each instance of a class and only one copy of static methods be create?
    Points will be rewarded for all helpful answers.

    Hi Sharma,
    Static methods is used to access statics attributes of a class. We use static attributes when we want to share the same attribute with all instances of a class, in this case if you chage this attribute through the instance A this change will change will be reflected in instance B, C........etc.
    I think that your question is correct -> a separate copy of instance method will be created for each instance of a class and only one copy of static methods be create ?
    "A static method does not require instance of class(to access) and it can directly be accessed by the class name itself"
    Static Method: call method class=>method.
    Instance Method: call method instance->method.
    Take a look at this wiki pages.
    [https://wiki.sdn.sap.com/wiki/x/o5k]
    [https://wiki.sdn.sap.com/wiki/x/ZtM]
    Best regards.
    Marcelo Ramos

  • The purpose of static methods ....?

    In lay mans terms can anyone tell me WHY we have static methods ?

    In lay mans terms can anyone tell me WHY we have
    static methods ?Static methods become class level methods and are no longer confined within the objects of the class.
    Static methods typically provide information about the class as a whole, such as the number of created objects etcetera. Another use is as an object factory. Instead of doing new all over the program you have a static create method you call to get new objects of the class.

  • Confused regarding static methods

    Hello guys,
    I like to know the only purpose of static method is to call a method with out creating
    instance of that class.
    I am totaly confused why and where to use static methods.
    Thanks in advance
    aneesh

    Look at the API docs for some of the static methods in classes like java.lang.String, java.lang.Integer, java.lang.Thread, etc.
    An object--an instance of a class--has state and behavior. The state is captured in the instance variables--the array that holds the characters of a String, the name, SS#, and hireDate fields of an Employee object, etc.
    Static methods are used when the operation you're performing isn't associated with any particular instance of that class--it doesn't use or modify the state of a particular object. The operation is associated with the class as a whole.
    For instance, Integer.parseInt(String). You're not operating on an existing Integer object. Rather you're creating a new Integer from a String. It's a utility or "helper" method of the Integer class.
    And yes, do read the tutorial.

  • Static methods

    Is creating a static method frowned upon in OO development? Is it only a matter of convenience by not having to instantiate?
    Any insight is appreciated.
    --Gregory
    quote: Don't throw away the old bucket until you know whether the new one holds water.

    Regardless of how many objects you have created, there is only 1 copy of the static variables in the memory. Its not just a matter of convenience but is used in certain conditions based on some requirements. A good example would be Singleton. There already is a kind of Singleton class in the standard Java class libraries:
    the Math class. This is a class that is declared final and all methods are declared static, meaning that the class cannot be extended. The purpose of the Math class is to wrap a number of common mathematical functions such as sin and log in a class-like structure, since the Java language does not support functions that are not methods in a class. You can use the same approach to a Singleton pattern, making it a final class. You can�t create any instance of classes like Math, and can only call the static
    methods directly in the existing final class.
    Another approach, suggested by Design Patterns, is to create Singletons using a static method to issue and keep track of instances. To prevent instantiating the class more than once, we make the constructor private so an instance can only be created from within the static method of the class.
    Hope that helps
    &#9824

  • Memory management with static methods

    I made a class with no attributes and only static methods with the purpose of maintaining as little as possible about it in memory. What information is kept in memory by the JVM about such a class ?
    Thanx in advance :)

    Static methods don't consume less memory than regular instance
    methods. Well, not exactly: a regular method requires a reference
    to an instance as a hidden additional parameter. Thus, specifying
    static for methods that don't access the object may actually save
    a few bytes. However, the code is not duplicated for each instance.
    Additionally, the JVM must keep any initialization values and the
    names of the class and the methods, as needed by reflection.
    Given suitable debugging options, local variables names and line
    number may be kept in memory as well. Finally, all hosekeeping
    info (gc, references and the like) must be kept in memory.

  • Static Methods in Rmi

    I have a static method in my class .
    Now i want to change my class to Distributed class
    So what to do with that static method ...
    I can't take in interface , so how i can call that method
    Sunil Virmani

    The pre condition of all the remote methods is that they should have been declared in the interface implementing RemoteInterface. Now its been discussed in detail in this forum already why we cannot have static methods declared in the interface therefore by nature not being polymorphic u cannot use static methods for the aforesaid purpose.

  • Static methods in encoded XML output stream

    I have a class designed to be instantiated, then initialized in several steps, one of them being the use of a static method declared in a separate class. The approach works fine in a Java program but when I attempt to devise a persistence delegate to handle the XML encoding of those steps, XMLEncoder objects to the use of a Statement object specifying a method that is not a member of the class being encoded. It keeps looking for the method in the target class and, not finding it, posts a failure.
    The persistence delegate exists in a separate module being designed to support serialization of classes in the target package. I can do a workaround by inserting a member method in the target class to wrap the static method in the other class but for reasons of coding economy prefer not to do that. And it seems to me this defeats the purpose of the persistence delegate. I want to design the persistence support module to fit the target package, not the other way around.
    Is it possible to encode a Statement object to invoke a separately-defined static method? If so, how do I code it?

    I'm trying to produce a statement instantiated as:
    *Statement stmt = new Statement(oldInstance, "myMethod", new Object[]{arguments});*
    where oldInstance is the instance of targetClass being persisted and myMethod is the name of a utility static method in a separate class that performs certain initializations. Next line is
    out.writeStmt(stmt)
    where out is the Encoder instance passed in to the initialize method of the persistence delegate. Encoder expects to find myMethod as a member of targetClass. When it doesn't it issues a message of the form:
    java.lang.Exception: Encoder: discarding statement targetClass.myMethod( arguments );
    The Javadoc description for Encoder.writeStatement confirms this, that the statement
    "... should be written entirely in terms of the callers environment ..."
    The Encoder doesn't have the other class in context at this point in the object graph being written and evidently isn't endowed with the ability to look outside of that context. If, instead of oldInstance in the Statement construction I put something like OtherClass.class, the result is that Encoder doesn't complain but simply ignores the statement and generates no output for it.
    Without going into discussion of why the target class and the utility method are designed like this, let me just say they are based on prudent design considerations and work well. I was hoping to write a persistence delegate without contorting the target class but thus far haven't found a way.

  • Can Static Methods be overridden ?

    My question is can static methods be overridden ?
    I found this thread [Can Static Method be overridden ?|http://forums.sun.com/thread.jspa?threadID=644752&start=0&tstart=0] .Since it was too old,i have created this new thread.
    According to that thread discussion, Java language states that static methods cannot be overridden.
    To which kajbj posted a program which did allow overriding of static methods.To quote him :
    I filed a bug report on it. I don't know if it's expected behaviour or not, but I expect the compiler to complain if you add @Override to a static method (since it can't be overridden)
    /Kaj This is one small program code which i wrote ,which did not allow static methods to be overridden,but no error as such was displayed.
    package fundamentals;
    class SuperClass
      public static String getName()
           return "HI,CLASS...SUPER CLASS";
      public int getAge()
           return 20;
    } // END OF SUPER CLASS
    public class SubClass extends SuperClass{
    public static void main(String[] args)
              SubClass objSubClass=new SubClass();
              SuperClass objSuperClass=new SubClass();
              System.out.println(objSubClass.getName());      // SUB CLASS
              System.out.println(objSuperClass.getName());   // SUPER CLASS
              System.out.println(objSubClass.getAge());        // SUB CLASS
              System.out.println(objSuperClass.getAge());     // SUPER CLASS
                     public    static String getName()
                       return "HI,CLASS...SUB CLASS";
                     public int getAge()
                        return 40;
    } // END OF MAIN CLASSWhich gives the O/P :
    HI,CLASS...SUB CLASS
    HI,CLASS...SUPER CLASS
    40
    40So,the static method was not overridden.
    But ,why was no error message displayed ?
    Also when i modify the subclass static method,by removing the static keyword as follows :
    public  String getName()
                       return "HI,CLASS...SUB CLASS";
                     }A Error Message as :
    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
         This instance method cannot override the static method from SuperClassis displayed.
    Why this message is displayed after i remove the static keyword ?
    So can we say that Java does not allow static method to be overridden but does not display a compile/run time error when this is done ?
    Is this a bug as stated by kajbj ?
    Please let me know if i am not clear.If this question has been answered somewhere else in this forum,kindly let me know.
    Thank you for your consideration.

    amtidumpti wrote:
    My question is can static methods be overridden ?
    I found this thread [Can Static Method be overridden ?|http://forums.sun.com/thread.jspa?threadID=644752&start=0&tstart=0] .Since it was too old,i have created this new thread.
    According to that thread discussion, Java language states that static methods cannot be overridden.
    To which kajbj posted a program which did allow overriding of static methods.To quote him :
    I filed a bug report on it. I don't know if it's expected behaviour or not, but I expect the compiler to complain if you add @Override to a static method (since it can't be overridden)
    /Kaj
    Sigh! Amti, are you being misleading on purpose? Kaj did not "post a program which did allow overriding of static methods." He posted a program which used the annotation @Override on a static method, like this:
    class A {
        public static void m() {}
    class B extends A {
        @Override public static void m() {}
    }He wondered why it didn't generate an error message. Well, it does now:
    A.java:6: method does not override or implement a method from a supertype
        @Override public static void m() {}
        ^
    1 error

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

  • Help with static method issue.

    Hi everyone,
    There's a recent thread on the forum along a similar vein as this one but I hope mine doesn't cause as much annoyance! My homework assignment involves implementing three interfaces provided by my professor in order to create weighted, undirected graphs. The classes I have to implement are Node, Edge and Graph. Here are the Edge and Node interfaces for reference; they weren't too hard to implement:
    public interface Edge {
         public Edge createEdge(String name, int ID, float weight);
         public Node getStartNode();
         public void setStartNode(Node n);
         public Node getEndNode();
         public void setEndNode(Node n);
         public String getName();
         public int getID();
         public float getWeight();
         public String toString();
    public interface Node {
         public Node createNode(String name, int ID, float weight);
         public Node[] getNeighbours();
         public Edge[] getEdges();
         public void addEdge(Edge e);
         public void removeEdge(Edge e);
         public String getName();
         public int getID();
         public float getWeight();
         public String toString();
    }Now, one of the graphs I should be aiming to create is this one ( [http://i35.tinypic.com/2iqn62d.gif|http://i35.tinypic.com/2iqn62d.gif] ) so I apologize for the code I'm about to show and its length. It's the Graph class:
    import java.util.ArrayList;
    public class Graph {
         public static void main(String [] args) {
              // Create all nodes
              int i = 1;
              Node food = new Node();
              food.createNode("Food", i, 0);
              i++;
              Node healthy = new Node();
              healthy.createNode("Healthy", i, 4f);
              i++;
              Node neutral = new Node();
              neutral.createNode("Neutral", i, 0);
              i++;
              Node unhealthy = new Node();
              unhealthy.createNode("Unhealthy", i, -4f);
              i++;
              Node orange = new Node();
              orange.createNode("Orange", i, 6f);
              i++;
              Node cabbage = new Node();
              unhealthy.createNode("Cabbage", i, 3f);
              i++;
              Node riceCake = new Node();
              unhealthy.createNode("Rice cake", i, 2f);
              i++;
              Node chocolate = new Node();
              unhealthy.createNode("Chocolate", i, -2f);
              i++;
              Node bacon = new Node();
              unhealthy.createNode("Bacon", i, -4f);
              i++;
              Node xmasPud = new Node();
              unhealthy.createNode("Christmas Pudding", i, -8f);
              i++;
              // Create all edges
              int n = 1;
              Edge food1 = new Edge();
              food1.createEdge("to healthy", i, -4.0f);
              food1.setStartNode(food);
              food1.setEndNode(healthy);
              n++;
              Edge food2 = new Edge();
              food2.createEdge("to neutral", i, 0);
              food2.setStartNode(food);
              food2.setEndNode(neutral);
              n++;
              Edge food3 = new Edge();
              food3.createEdge("to unhealthy", i, -4f);
              food3.setStartNode(food);
              food3.setEndNode(unhealthy);
              n++;
              Edge healthy1 = new Edge();
              healthy1.createEdge("to orange", i, 4f);
              healthy1.setStartNode(healthy);
              healthy1.setEndNode(orange);
              n++;
              Edge healthy2 = new Edge();
              healthy2.createEdge("to cabbage", i, 2f);
              healthy2.setStartNode(healthy);
              healthy2.setEndNode(cabbage);
              n++;
              Edge neutral1 = new Edge();
              neutral1.createEdge("to rice cake", i, 2f);
              neutral1.setStartNode(neutral);
              neutral1.setEndNode(riceCake);
              n++;
              Edge unhealthy1 = new Edge();
              unhealthy1.createEdge("to chocolate", i, -2f);
              unhealthy1.setStartNode(unhealthy);
              unhealthy1.setEndNode(chocolate);
              n++;
              Edge unhealthy2 = new Edge();
              unhealthy2.createEdge("to bacon", i, -4f);
              unhealthy2.setStartNode(unhealthy);
              unhealthy2.setEndNode(bacon);
              n++;
              Edge unhealthy3 = new Edge();
              unhealthy3.createEdge("to Christmas pudding", i, -8f);
              unhealthy3.setStartNode(unhealthy);
              unhealthy3.setEndNode(xmasPud);
              n++;
              // Assign edges to edgeList
              food.edgeList.add(food1);
              food.edgeList.add(food2);
              food.edgeList.add(food3);
              // Add node to nodeList
              nodeList.add(food);
              healthy.edgeList.add(healthy1);
              healthy.edgeList.add(healthy2);
              nodeList.add(healthy);
              neutral.edgeList.add(neutral1);
              nodeList.add(neutral);
              unhealthy.edgeList.add(unhealthy1);
              unhealthy.edgeList.add(unhealthy2);
              unhealthy.edgeList.add(unhealthy3);
              nodeList.add(unhealthy);
              // Now convert to arrays
              Node[] nodeArray = new Node; // Nodes
              nodeList.toArray(nodeArray);
              Edge[] edgeArray = new Edge[n]; // Edges
              food.edgeList.toArray(edgeArray);
              healthy.edgeList.toArray(edgeArray);
              unhealthy.edgeList.toArray(edgeArray);
              // Now turn it all into a graph
              createGraph("Food", 1, nodeArray, edgeArray, food); // doesn't work!
         public Graph createGraph(String name, int ID, Node[] nodes, Edge[] edges,
                   Node root) {
              graphName = name;
              graphID = ID;
              graphNodes = nodes;
              graphEdges = edges;
              graphRoot = root;
              return null;
         public String getName() {
              return graphName;
         public Edge[] getEdges() {
              return graphEdges;
         public void addEdge(Edge e) {
         public Edge getEdge(String name, int ID) {
              return null;
         public void removeEdge(Edge e) {
         public Node[] getNodes() {
              return graphNodes;
         public void addNode(Node n) {
              nodeList.add(n);
         public Node getNode(String name, int ID) {
              int ni = nodeList.indexOf(name);
              Node rNode = nodeList.get(ni);
              return rNode;
         public void removeNode(Node n) {
              nodeList.remove(n);
         public void setRoot(Node n) {
              graphRoot = n;
         public Node getRoot() {
              return graphRoot;
         private String graphName;
         private int graphID;
         private Node[] graphNodes;
         private Edge[] graphEdges;
         private Node graphRoot;
         private static ArrayList<Node> nodeList = new ArrayList<Node>();
    }The problem I have is that I don't know how to get around the fact that I'm making a static reference to the non-static method *createGraph*. I'd really appreciate your help. Thanks for your time!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    GiselleT wrote:
    public interface Edge {
         public Edge createEdge(String name, int ID, float weight);
    I want to kick your professor right in the grapes for this bit of idiocy. It's at the source of your problems.
    This looks very fishy and very bad. I wouldn't expect an Edge to create another Edge. Likewise for Node and Graph. You might have static factory methods in these classes, but by defining it in the interfaces, these methods have to be non-static. This leads to such ridiculous code as you have like this:
    Edge uselessEdge = new Edge();
    Edge actualEdge = uselessEdge.createEdge("abc", 1, 2.34);It's not your fault that it's useless. That's the way you have to do it with that senseless requirement.
    The problem I have is that I don't know how to get around the fact that I'm making a static reference to the non-static method createGraph.
    Static reference in non-static context errors are always addressed the same way: Either make the member in question static (usually the wrong choice) or create an instance.
    In this case, you need to do like you did with Edge, and create a useless dummy Graph whose only purpose is to create other Graphs:
    Graph graph = uselessGraph();
    Graph actualGraph = uselessGraph.createGraph(...);Then, inside the createGraph method, you'll create a Graph with new and do thatGraph.name = name; and so on for each of the parameters/members.
    Really, though, this is just an awful, awful approach though. Are you sure your prof really requires Edge to have a non-static createEdge method, and so on?

  • Static method vs synchronisation

    Hi,
    A fundamental query.
    If i am declaring a method as static, can i also declare it as sunchronized? i.e. can i have something like
    public static synchronized sss(){
    xxx
    If a method is static, there is only one instance in the memory. Correspondingly, only one client can execute it at a time. in which case it is automatically synchronized.
    Pl correct my reasoning.
    When do we have the requirement of having a static method, or probably a singleton??
    Thanks,
    Prashant Gupta

    Hi,
    A fundamental query.
    If i am declaring a method as static, can i also declare it as sunchronized? i.e. can
    i have something like
    public static synchronized sss(){
    xxx
    }?Yes, static methods can be synchronized which means that when any thread is running within a synchronized static method of class C, no other thread may enter a static synchronized method of that class. In other words, the monitor acquired by a static synchronized method is the Class itself while the monitor acquired by a non-static synchronized method is the object refered to by 'this'.
    If a method is static, there is only one instance in the memory. Correspondingly,
    only one client can execute it at a time. in which case it is automatically synchronized.There is (in most circumstances) a single copy of the definition (bytecodes representing all methods - static or not - and static fields) of of a class. However, any number of threads may be executing within any section of code unles that code is guarded by a synchronized block or within a synchronized method. In that case, no two threads can enter (well, actually be runnable within - Object.wait() has special implications) a synchronized block monitored by the same object.
    When do we have the requirement of having a static method, or
    probably a singleton??Not sure what you are asking here. You define static methods when there is behavior you want to implement that does not need to have access to instance (non-static) fields or methods and which would never need to be overridden (for purposes of polymorphism) by derived classes.
    Wen needing a singleton, you have a choice of defining a "true singleton" (i.e. a class with a private constructor, some sort of static getInstance() method, with the bulk of its methods anf fields are non-static) or defining a class whose methods are all static and whose fields are also all static. Singletons. Use the one that fits you needs the best.
    Chuck

  • Compilation error while calling static method from another class

    Hi,
    I am new to Java Programming. I have written two class files Dummy1 and Dummy2.java in the same package Test.
    In Dummy1.java I have declared a static final variable and a static method as you can see it below.
    package Test;
    import java.io.*;
    public class Dummy1
    public static final int var1= 10;
    public static int varDisp(int var2)
    return(var1+var2);
    This is program is compiling fine.
    I have called the static method varDisp from the class Dummy2 and it is as follows
    package Test;
    import java.io.*;
    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    and when i compile Dummy2.java, there is a compilation error <identifier > expected.
    Please help me in this program.

    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    }test+=Dummy1.varDisplay(var3);
    must be in a method, it cannot just be out somewhere in the class!

  • 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 );
       }

  • Using HttpServletRequest object to share variables between static methods.

    Does anyone know of the overhead/performance implications of using the HttpServletRequest object to share variables between a static method and the calling code?
    First, let me explain why I am doing it.
    I have some pagination code that I would like to share across multiple servlets. So I pulled the pagination code out, and created a static method that these servlets could all use for their pagination.
    public class Pagination {
         public static void setPagination (HttpServletRequest request, Config conf, int totalRows) {
              int page = 0;
              if (request.getParameter("page") != null) {
                   page = new Integer(request.getParameter("page")).intValue();
              int articlesPerPage = conf.getArticlesPerPage();
              int pageBoundary = conf.getPageBoundary();
                int numOfPages = totalRows / articlesPerPage;  
                // Checks if the page variable is empty (not set)
                if (page == 0 || (page > numOfPages && (totalRows % articlesPerPage) == 0 && page < numOfPages + 1)) {    
                 page = 1;  // If it is empty, we're on page 1
              // Ex: (2 * 25) - 25 = 25 <- data starts at 25
             int startRow = page * articlesPerPage - (articlesPerPage);
             int endRow = startRow + (articlesPerPage);           
             // Set array of page numbers.
             int minDisplayPage = page - pageBoundary;
             if (minDisplayPage < 1) {
                  minDisplayPage = 1;     
             int maxDisplayPage = page + pageBoundary;
             if (maxDisplayPage > numOfPages) {
                  maxDisplayPage = numOfPages;     
             int arraySize = (maxDisplayPage - minDisplayPage) + 1;
             // Check if there is a remainder page (partially filled page).
             if ((totalRows % articlesPerPage) != 0) arraySize++;
             // Set array to correct size.
             int[] pages = new int[arraySize];
             // Fill the array.
             for (int i = 1; i <= pages.length; i++) {
                  pages[i - 1] = i;
             // Set pageNext and pagePrev variables.
             if (page != 1) {
                  int pagePrev = page - 1;
                  request.setAttribute("pagePrev", pagePrev);
             if ((totalRows - (articlesPerPage * page)) > 0) {
                 int pageNext = page + 1;
                 request.setAttribute("pageNext", pageNext);
             // These will be used by calling code for SQL query.
             request.setAttribute("startRow", startRow);
             request.setAttribute("endRow", endRow);
             // These will be used in JSP page.
             request.setAttribute("totalRows", totalRows);
             request.setAttribute("numOfPages", numOfPages);
             request.setAttribute("page", page);
             request.setAttribute("pages", pages);          
    }I need two parameters from this method (startrow and endrow) so I can perform my SQL queries. Since this is a multithreaded app, I do not want to use class variables that I will later retrieve through methods.
    So my solution was to just set the two parameters in the request and grab them later with the calling code like this:
    // Set pagination
    Pagination.setPagination(request, conf, tl.getTotalRows());
    // Grab variables set into request by static method
    int startRow = new Integer(request.getAttribute("startRow").toString());
    int endRow = new Integer(request.getAttribute("endRow").toString());
    // Use startRow and endRow for SQL query below...Does anyone see any problem with this from a resource/performance standpoint? Any idea on what the overhead is in using the HttpServletRequest object like this to pass variables around?
    Thanks for any thoughts.

    You could either
    - create instance vars in both controllers and set them accordingly to point to the same object (from the App Delegate) OR
    - create an instance variable on the App Delegate and access it from within the view controllers
    Hope this helps!

Maybe you are looking for