Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2011
    Posts
    3
    Rep Power
    0

    Default Using variables inside methods?

    Is it acceptable to use variables you have established outside of a method, inside of a method?

    For example, say I want to clear all textboxes, and this needs to happen under lots of different conditions. Could I write a method to specifically clear each actual textbox (not using a formal perimeter or anything), even though they were created outside of the method?

    It works fine, I just want to know if its bad practice or if I'm gonna take a hit on my project grade.

    Just to make sure I'm being clear:

    outside method:

    private JTextField jftPlayer1 = new JTextField(10);
    private JTextField jftPlayer2 = new JTextField(10);

    Method:

    private void resetAll()
    {

    jftPlayer1.setText("");
    jftPlayer2.setText("");

    }

    And of course, call the method:

    resetAll();

    Every example from my textbook uses variables declared inside the method and/or formal parameters. None use variables actually declared outside the method.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Your example is fine and I don't see a better way to do this. Just be sure to provide javadocs for all public methods, and perhaps some private ones (like the one above).

  3. #3
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,663
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Forty0ztoFreedom View Post
    Is it acceptable to use variables you have established outside of a method, inside of a method?
    A variable defined outside of any method is (by definition) a (static) member variable. Suppose you're not allowed to manipulate such a variable inside a method then you're not allowed to manipulate it anywhere because there is no ordinary code allowed outside the body of any method. So, yes, your example is fine.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. how to call or use methods inside interface?
    By akhmad in forum New To Java
    Replies: 2
    Last Post: 11-10-2010, 10:55 AM
  2. Naming variables inside a cicle
    By jack DANIEL's in forum New To Java
    Replies: 5
    Last Post: 11-01-2010, 08:13 PM
  3. Replies: 4
    Last Post: 04-03-2009, 07:36 AM
  4. variables-methods
    By Warren in forum New To Java
    Replies: 1
    Last Post: 11-28-2007, 05:14 PM
  5. significance of static variables and methods
    By imran_khan in forum New To Java
    Replies: 4
    Last Post: 08-02-2007, 10:52 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
  •