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

Similar Messages

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

  • Can you override a public static method?

    Can you override a public static method?

    A static method belongs to a class, not to a particular object, because you can call them without having an object instantiated. Methods are over rided which are inherited from an object. Since Static methods (although inherited) are not bound to a particular object, are not overridden.
    Though you have a method in the subclass with the same signatures but if you try to call super.____() you will get the error
    non-static variable super cannot be referenced from a static context

  • Implementing interface with static method?

    Hi,
    I need to implement an interface with a static method. I tried to do it both with the interface method static and non-static, but it don't seam to work! Does it work?
    How can I make a work around?
    Thanks!

    Interfaces are designed to provide a contract that a particular object instance guarantees for it's Clients.
    Since a static method does not relate to any particular object instance there is no contract to define...hence you can't have an interface for static methods...
    What you could do however is return an object via a static method that does provide the implementation of the interface...
    i.e.public class MyClass
        static private String myInterfaceImpl = "<some class>";
        static public MyInterface getInterface ()
             return (MyInterface) MyClass.class.forName (MyClass.myInterfaceImpl).newInstance ();
    }That would return an object that provides the interface. I would presume you need the static method so that you don't have to pass around references to a particular object...this method gets around that...you could also create a single object at start up time and return a reference to that eveytime...
    Also, in a way static methods do define an interface...

  • Variables declared in static methods

    Hi,
    I've got a question. Are variables (primitive and Objects) declared inside
    static methods stored in a same memory space or are the stored separately?
    I'm creating a helper class that contains static methods that canno be placed in any object in my object map.
    For example
    public static String SampleMethod(String passedString)
    String str = new String(passedString);
    ...do some more processing and sleeping
    return str;
    Let's say Object1 and Object2 make a call to SampleMethod. Object1 passes "Object1" and right before the Object1's SampleMethod returns str, Object2 makes a call passing "Object2". What would be the value of str for Object1's SampleMethodCall?
    Thanks :)

    If speaking about class members, then static members are stored in one place and are properties of the class, when non-staic members are stored in an object's memory and a properties of an object.
    However in your sample it's not the case.
    Local variables of a method are most likely allocated on registers or on stack (thus being rather properties of the call to a method).
    Thus in your case calls to SampleMethod done by Object1 and Object2 simultaneously (if you managed to do this in two different threads) will use different memory (most likely in threads' own stacks).
    As for calls to "new String" inside your method, the new string memory will be allocated dynamically each time the new operator is called, thus producing two different objects. The references to them will be stored in two local variables of two independent calls.
    Finally, Object1 will get a copy of "Object1" and Object2 will get a copy of "Object2", as expected.
    Vit

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

  • 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

  • Non-static method cannot be referenced from a static context....again sry

    Hey, I know you guys have probably seen a lot of these, but its for an assignment and I need some help. The error I'm getting is: non-static method printHistory() cannot be referenced from a static context. Here are the classes effected
    public class BankAccount {
    private static int nextAccountNumber = 1000;
    //used to generate account numbers
    private String owner; //name of person who owns the account
    private int accountNumber; //a valid and unique account number;
    private double balance; //amount of money in the account
    private TransactionHistory transactions; //collection of past transactions
    private Transaction transaction;
    //constructor
    public BankAccount(String anOwnerName){
    owner = anOwnerName;
    accountNumber = nextAccountNumber++;
    balance = 0.0;
    transactions = new TransactionHistory();
    //public String getOwner() {
    public void deposit(double anAmount ){
         balance=balance+anAmount;
         transaction=new Transaction(TransactionType.DEPOSIT,accountNumber,anAmount,balance);
         transactions.add(transaction);
    //public void withdraw(double anAmount){
    //public String toString() {
    ***public void printHistory(){
         TransactionHistory.printHistory();
    AND
    public class TransactionHistory {
    final static int CAPACITY = 6; //maximum number of transactions that can be remembered
    //intentionally set low to make testing easier
    private Transaction[] transactions = new Transaction[CAPACITY];
    //array to store transaction objects
    private int size = 0;
    //the number of actual Transaction objects in the collection
    public void add(Transaction aTransaction){
         if (size>5){
         transactions[0]=transactions[1];
         transactions[1]=transactions[2];
         transactions[2]=transactions[3];
         transactions[3]=transactions[4];
         transactions[4]=transactions[5];
         transactions[5]=aTransaction;     
         transactions[size]=aTransaction;
         size=size++;
    public int size() {
         return size;
    ***public void printHistory() {
         for(int i=0;i<6;i++){
              System.out.println(transactions);
    //public void printHistory(int n){
    The project still isn't finished, so thats why some code is commented out. The line with *** infront on it are the methods directly effected, I think. Any help would be great.

    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).
    ~

  • Non-static method paint cannot be referenced from static context

    i cant seem to figure out this error dealing method paint:
    public class TemplateCanvas extends Canvas implements Runnable {
        //static
        public static final int STATE_IDLE      = 0;
        public static final int STATE_ACTIVE    = 1;
        public static final int STATE_DONE      = 2;
        private int     width;
        private int     height;
        private Font    font;
        private Command start;   
        private int state;
        private String message;
        public TemplateCanvas() {
            width = getWidth();
            height = getHeight();       
            font = Font.getDefaultFont();
            //// set up a command button to start network fetch
            start = new Command("Start", Command.SCREEN, 1);
            addCommand(start);
        public void paint(Graphics g) {
            g.setColor(0xffffff);
            g.fillRect(0, 0, width, height);
            g.setColor(0);
            g.setFont(font);
            if (state == STATE_ACTIVE) {
                Animation.paint(g);
            } else if (state == STATE_DONE) {
                g.drawString(message, width >> 1, height >> 1, Graphics.TOP | Graphics.HCENTER);
        public void commandAction(Command c, Displayable d) {
            if (c == start) {
                removeCommand(start);
                //// start fetching in a new thread
                Thread t = new Thread(this);
                t.start();
        public void run() {
            state = STATE_ACTIVE;
            //// start network fetch
            Network network = new Network();
            network.start();
            //// start busy animation
            Animation anim = new Animation(this);
            anim.start();
            //// wait for network to finish
            synchronized (network) {
                try {
                    wait();
                } catch (InterruptedException ie) { }
            //// end animation
            anim.end();
            //// get message from network
            message = network.getResult();
            //// repaint message
            state = STATE_DONE;
            repaint();
    }TemplateCanvas.java:38: non-static method paint(javax.microedition.lcdui.Graphics) cannot be referenced from a static context

    Animation.paint(g); paint() is not a static method. That means you have to call it on an instance of an Animation class (an object), not on the class itself. This is designed this way because the paint() method uses variables that have to be instantiated, so if you don't have an instance to use, it can't access the variables it needs. Static methods don't use instance variables, they only use what's passed in to them, so they don't need to be called on an object. Hope that was clear.

  • Non-static method setUp() cannot be referenced  (error)

    Hi;
    I have this error
    "findContainer.java": non-static method setUp() cannot be referenced from a static context at line 10, column 26
    everytime i am trying to make this call
    jade.core.AddContTry.setUp();in
    public class findContainer {
      public findContainer() {}
        public void sUp(){
        System.out.println("please wait, this is first try to find he agents in the main container"+"\n");
        jade.core.AddContTry.setUp();
    this setup() method
    is written as follows
    public void AddContTry () {
    public void setUp(){
      AID[] list= null;
      try {
        MyMainContainer = myprofile.getMain();
        System.out.println("\n"+"This is the new container created in case of failure"+"\n");
        list = MyMainCont.agentNames();
        for (int i=0; i<list.length; i++){
          System.out.println("names = " + list.toString() + " \n");
    catch (ProfileException pe) { System.out.println("there is not main container");
    could you please help me?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    My guess is that it is throwing a NullPointerException because you have not set 'a' to be anything.
    The sample code you provided does not make sense.
    AddContTry is a method in the code but you are using it like a class.
    You have to set the following before you can use the object 'a'
    AddContTry a = // something
    I am just guessing here but can you write
    AddContTry a = new AddContTry();
    a.setUp();
    Note, If this is the case, the code in setUp should be in the constructor.

  • Non-static method getRealPath cannot be referenced from a static context

    Hi, I'm fairly new to java and servlets, I get the following error referencing the line denoted in the code snippet with a ">>" I don't understand why I am getting this error message?
    Message: non-static method getRealPath(java.lang.String) cannot be referenced from a static context
    public class events extends HttpServlet implements SingleThreadModel {
      private static final String CONTENT_TYPE = "text/html";
      //Initialize global variables
      public Document xmlDocument;
      public HttpSession theSession;
      public RequestDispatcher pageInit;
      public RequestDispatcher pageHeader;
      public RequestDispatcher pageFooter;
      public String path;
      public void setPath(){
    path = getServletContext.getRealPath( "/" );  }
      public void init() throws ServletException {
      }

    Ok More Code, I am weary of posting too much? I don't know why come to think of it?
    package altitude;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    import org.jdom.*;
    import altitude.sysVar;
    public class events extends HttpServlet implements SingleThreadModel {
      private static final String CONTENT_TYPE = "text/html";
      //Initialize global variables
      public Document xmlDocument;
      public HttpSession theSession;
      public RequestDispatcher pageInit;
      public RequestDispatcher pageHeader;
      public RequestDispatcher pageFooter;
      public String path;
      public void getRealPath(){
        path = ServletContext.getRealPath( "/" );
      public void init() throws ServletException {
      //Process the HTTP Get request
      public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        //Initialise some Global Variables
        theSession = request.getSession( true );
        doPage( request, response );
      //Process the HTTP Post request
      public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        //Initialise some Global Variables
        theSession = request.getSession( true );
        doPage( request, response );
    public void doPage( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        //Initialise the variables and get the parameters from the query string.
        String eventID = request.getParameter( "eventID" );
        String dateFrom = request.getParameter( "dateFrom" );
        String dateTo = request.getParameter( "dateTo" );
        theSession.setAttribute( "Page Title", sysVar.servletTitle_events);
        Calendar theCalendar = Calendar.getInstance();
        RequestDispatcher pageInit = request.getRequestDispatcher( sysVar.servlet_initSession );
        pageInit.include( request, response );
        RequestDispatcher pageHeader = request.getRequestDispatcher( theSession.getAttribute( "Skin Directory" ) + sysVar.page_header );
        RequestDispatcher pageBody = request.getRequestDispatcher( sysVar.servletJsp_events );
        RequestDispatcher pageFooter = request.getRequestDispatcher( theSession.getAttribute( "Skin Directory" ) + sysVar.page_footer );
        //Initailize the site for this visitor this sets up the skin, and any customisations that may exist.
        //load variables, objects in to the session
        theSession.setAttribute( "Xml Document Object",  path + sysVar.data_events );
        pageHeader.include( request, response );
        pageBody.include( request, response );
        pageFooter.include( request, response );
        //remove the variables and the objects from the session
        theSession.setAttribute( "Xml Document Object", "" );
      //Clean up resources
      public void destroy() {
    }

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

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • Using static methods to instantiate an object

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

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

  • More than one entity found for a single-object find method

    Hi everyone...
    I have this error when my webservice is running..I don't know what it means and what would be the best solution..
    <pns:message>More than one entity found for a single-object find method.</pns:message>
    it throws an Exception..
    Thanks!

    = More than one row found in a DB with the "unique" key supplied...
    Your method is returning an object where it should return a collection ?
    Enjoy

Maybe you are looking for