I’ve been learning Java for the past year in my free time, and so far, I have come across nothing on how to use variables correctly. By this, I mean, should I prefer to use instance variables, or just use variables in a single method.
For example, this is a piece of code I’ve written:
public class arsenalTroop {
String[][] troopStats;
String[][] weaponStats;
String[][] armorStats;
String[][] animalStats;
String[] troops;
String[] weapon;
String[] armor;
String[] animal;
JLabel[] troopsArray;
int troopTotal;
int weaponTotal;
int armorTotal;
int lordTotal;
int animalTotal;
JFrame arsenalLordFrame = new JFrame();
JTextField name = new JTextField();
JLayeredPane lP = new JLayeredPane();
JLayeredPane fP = new JLayeredPane();
JLayeredPane ldP= new JLayeredPane();
JLabel siegeLabel = new JLabel();
JComboBox weaponCB;
JComboBox armorCB;
JComboBox animalCB;
JLabel siegeText = new JLabel();
JButton addWep = new JButton();
JButton addName = new JButton();
JButton addArmor = new JButton();
JButton addAnimal = new JButton();
JButton ntr = new JButton();
JButton nwe = new JButton();
JButton nar = new JButton();
JButton nan = new JButton();
JButton newWeaponButtonArray[] = new JButton[6];
JButton newArmorButtonArray[] = new JButton[6];
JButton newAnimalButtonArray[] = new JButton[6];
Border whiteBorder = BorderFactory.createLineBorder(Color.white);
Border greyBorder = BorderFactory.createLineBorder(Color.gray);
boolean[] weaponFree = new boolean[6];
boolean[] armorFree = new boolean[6];
boolean[] animalFree = new boolean[6];
JButton done = new JButton();
public void arsenalTroopGui() {
As you can see, all of the variables I’m going to use are instance variables, so what i’m asking is, should I do this, or should I try to limit most of my variables to be within each method that they’d be used in?
You should use instance variables [fields] if the class has state, and it is important to it.
You should use local variables [or method variables] when it is specific for each run of the method.
Note that it is not only coding style issue, think what will happen if you declare all your variables as instance variables – and then run a method concurrently twice. It will cause the invokations of the methods to change the variables of each other, while this issue doesn’t happen for local variables.