Results 1 to 5 of 5
  1. #1
    talktofrank is offline Member
    Join Date
    Oct 2009
    Posts
    1
    Rep Power
    0

    Default referencing objects from static method

    Hi, having a little trouble with a program, any help would be greatly appreciated!

    Basically I have a Menu class with one static Main() method.
    From this class a user has a choice by typing into terminal, and one of the choices is to display all information that will have been stored in an instance of my SortedLinkedList class (a subclass of LinkedList).
    The instances of SLL are created in an InputReader class that reads books and users from a file and stores them in seperate SLLs.

    So my question is, how can I print out the contents of these SLLs (by calling the overwritten toString() method) from the static method in Menu.

    Or generically speaking, I think the question is:
    How can I can call a method on an object from a static method in another class?

    Thanks

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    By using a reference to that "object", of course.

  3. #3
    literallyjer is offline Member
    Join Date
    Oct 2009
    Posts
    25
    Rep Power
    0

    Default

    The object that you are calling the method on either has to be static or you have to create that object from within the static method (or within a statically scoped block).

  4. #4
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    Quote Originally Posted by literallyjer View Post
    The object that you are calling the method on either has to be static or you have to create that object from within the static method (or within a statically scoped block).
    Not necessarily. The object reference can also be passed to the method as an argument. Which is the better way of doing this, unless, maybe, the "object" in question is a singleton.

  5. #5
    literallyjer is offline Member
    Join Date
    Oct 2009
    Posts
    25
    Rep Power
    0

Similar Threads

  1. Static method cannot make new objects?
    By zerkz in forum New To Java
    Replies: 2
    Last Post: 10-15-2009, 03:17 AM
  2. non-static method cannot be referenced from a static context.
    By blackstormattack in forum New To Java
    Replies: 5
    Last Post: 05-07-2009, 04:05 AM
  3. Replies: 1
    Last Post: 02-10-2009, 10:03 AM
  4. Non-Static method in static context error
    By wizmang in forum New To Java
    Replies: 4
    Last Post: 04-24-2008, 08:51 AM
  5. Replies: 1
    Last Post: 08-07-2007, 05:05 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •