xxxxxxxxxx
// In Java, a static variable belongs to the class rather than an instance of the class.
// It is shared among all instances of the class and accessible through the class itself.
public class MyClass {
public static int staticVariable; // Declaring a static variable
public static void main(String[] args) {
MyClass myObj1 = new MyClass();
MyClass myObj2 = new MyClass();
// Accessing the static variable using the class name
MyClass.staticVariable = 10;
System.out.println(myObj1.staticVariable); // Output: 10
System.out.println(myObj2.staticVariable); // Output: 10
myObj1.staticVariable = 20; // Modifying the static variable
System.out.println(myObj1.staticVariable); // Output: 20
System.out.println(myObj2.staticVariable); // Output: 20
}
}
xxxxxxxxxx
// A static variable is shared among all objects of a class
class Slogan {
String phrase; // string description of slogan
static int count; // slogan count
public Slogan(String phrase) {
this.phrase = phrase;
count++;
}
}
public class SloganCounter {
public static void main(String[] args) {
Slogan slg1 = new Slogan("Live free or die!");
Slogan slg2 = new Slogan("Don't worry, be happy!");
System.out.println("Slogans count: " + Slogan.count);
// Above outputs: Slogans count: 2
}
}
xxxxxxxxxx
Person notReallyAPerson = null;
notReallyAPerson.qtdone++; // this works!