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:
but then when wrote Tet tet2 = new Tet(4, 5);
the following diagram happened and a was updated with the new value as it's shared :
so both instances of Tet have that variable called a which is shared meaning if you updated a using any of the 2 instance , it's updated in the second instance also.
also in C language, making the variable static
means that it's only one instance and also private to the file meaning you can't extern that variable to any other file