Results 1 to 3 of 3
Thread: Using variables inside methods?
- 04-08-2011, 06:51 PM #1
Member
- Join Date
- Mar 2011
- Posts
- 3
- Rep Power
- 0
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.
-
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).
- 04-08-2011, 07:36 PM #3
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,405
- Blog Entries
- 7
- Rep Power
- 17
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,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
Similar Threads
-
how to call or use methods inside interface?
By akhmad in forum New To JavaReplies: 2Last Post: 11-10-2010, 09:55 AM -
Naming variables inside a cicle
By jack DANIEL's in forum New To JavaReplies: 5Last Post: 11-01-2010, 07:13 PM -
How to get methods to see variables in other methods
By ejs7597 in forum New To JavaReplies: 4Last Post: 04-03-2009, 06:36 AM -
variables-methods
By Warren in forum New To JavaReplies: 1Last Post: 11-28-2007, 04:14 PM -
significance of static variables and methods
By imran_khan in forum New To JavaReplies: 4Last Post: 08-02-2007, 09:52 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks