We will summarize the differences between instance variables, local variables, and class variables.
-A variable declared with ** static ** --Has a value common to all instances of the class. It is also called ** class variable ** because it has a value attached to the class.
Variables defined directly under the class ** and outside the ** method **
A variable declared in ** in a method ** There is no problem even if you define a local variable with the same name as an instance variable or class variable **! !! !!
public class Main{
public static void main(String[] args){
Party P1 = new Party();
Party P2 = new Party();
Party.budget = 10000;
P1.participants = 5;
P1.remain(); //budget outputs as 9500
System.out.println(Party.budget); //9500 and output
System.out.println(P2.budget); //9500 and output
P2.participants = 10;
P2.remain(); //8500 and output
System.out.println(Party.budget); //8500 and output
System.out.println(P1.budget); //8500 and output
}
}
class Party {
int participants; //Instance variables
static int budget; //static variable (class variable)
void remain(){
int expense = 100 * participants; //Local variables
budget -= expense;
System.out.println(budget);
}
}
**-When having a local variable ** with the same name as the instance variable **
public class Main{
public static void main(String[] args){
Party P1 = new Party();
Party P2 = new Party();
Party.budget = 10000;
P1.remain(); //budget outputs as 8000
System.out.println(Party.budget); //8000 and output
System.out.println(P2.budget); //8000 and output
P2.remain(); //6000 and output
System.out.println(Party.budget); //6000 and output
System.out.println(P1.budget); //6000 and output
}
}
class Party {
int participants; //Instance variables
static int budget; //static variable (class variable)
void remain(){
int participants = 20; //A local variable with the same name as an instance variable
System.out.println(participants);
budget -= participants*100;
System.out.println(budget);
}
}