Methods without creating an object?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nickburton
    New Member
    • Oct 2008
    • 2

    Methods without creating an object?

    Hi there, I am new to Java and the concept of requiring a class/object to do everything..

    I am creating a menu based program and hence need to re-use segments of code. If I was writing in C, I would just create a method above the main program and then call that method each time I wanted to, for example, display a menu.

    The program I'm writing has two main classes from which I create objects to store data (imagine a 2D array of data but have used two arrays of objects instead). But let's say I want to re-use code that does not necessarily relate to either of the classes/objects, it's just the menus, etc. Would I create a separate class/object for that purpose? I am struggling with this for some reason..

    Lil help? Thanks in advance!

    Nick
  • Bassem
    Contributor
    • Dec 2008
    • 344

    #2
    High Nick,

    You can write Methods (Functions in C) in java in the program class (above the main method), truly above or down.

    But you have one restriction is to declare the method as static, which mean that you can invoke ( call ) it from the class contains it, not using a specific object.
    Just like the Main method.
    Try this:

    public static int MyMethodName (int x)
    {
    return x;
    }

    static void Main (string[] args)
    {
    System.out.Prin tln( MyMethodName (5) );
    }
    Thanks
    Bassem

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Originally posted by nickburton
      But let's say I want to re-use code that does not necessarily relate to either of the classes/objects, it's just the menus, etc.
      Well, there you are: there's a third class probably named Menus or MenuHandler or whatever. Stick your methods in an object of that class. Of course you can go for the static method variant but sooner or later that'll shoot you in the back. And besides: those static methods also have to belong to some class.

      kind regards,

      Jos

      Comment

      Working...