Issue
I'm pretty new to Java. I've just written a small example to observe the effects of access modifiers. Maybe the code does not make much sense since I'm just testing things out.
The first code snippet looks like this:
class Tet {
static double a;
double b;
public Tet(double a, double b){
this.a=a;
this.b=b;
}
public void get(){
a=5;
}
public static void main(String[] args){
Tet tet1 = new Tet(2, 5);
Tet tet2 = new Tet(4, 5);
System.out.println(tet1.a);
a=4;
System.out.println(tet1.a);
tet1.get();
System.out.println(tet1.a);
System.out.println(a);
}
}
After this, I made some changes to the code and compiled it again:
class Tet {
static double a;
double b;
public Tet(double a, double b){
this.a=a;
this.b=b;
}
public static void get(){
a=5;
}
public static void main(String[] args){
Tet tet1 = new Tet(2, 5);
Tet tet2 = new Tet(4, 5);
System.out.println(a);
get();
System.out.println(tet1.a);
System.out.println(a);
System.out.println(tet2.a);
}
}
After it runs, the cmd looks like this: enter image description here
I really don't know where is number 4 coming from.
Solution
- All Java's variables must be known at compile time unlike Python, in either way:
- declare local variable (in this case, declare
int a
in yourmain
) - qualify variable (in this case, change to
Tet.a
) - (
import
variable, but it's a bit longer and redundant this case)
- declare local variable (in this case, declare
- You're touching
static
area - an special storage.static
variables are shared across all class instances. So:
public static void main(String[] args){
Tet tet1 = new Tet(2, 5); // set Tet's `a` to 2
// update `a` to 4.
// `a` is shared across `tet1` and `tet2`!
Tet tet2 = new Tet(4, 5);
// Watch out, `Tet`'s `a` is shared! It'll output 4
System.out.println(tet1.a);
System.out.println(tet1.a);
tet1.get(); // `get`, but updates `a` to 5
System.out.println(tet1.a); // This will be 5 as well
}
If this answer resolves your question, consider mark this as "resolved" :)
Answered By - user-id-14900042
Answer Checked By - Terry (JavaFixing Volunteer)