public static void main(String[] args) {
Person p1 = new
Person("Gogo", 14);
Person p2 = new Person("Momo", 23);
Person p3 = new Person("Yoyo", 19);
p1. setLicenseAge(18); // same as: p2. setLicenseAge (18);
System.out.println(p1.toString());
System.out.println(p2.toString());
System.out.println(p3.toString());
System.out.println("Changing adult age to be 21:");
p2.setLicenseAge(21); // same as: p3.setLicenseAge (21);
System.out.println(p1.toString());
System.out.println(p2.toString());
System.out.println(p3.toString());
} // main
דוגמא:
Person
public class Person {
private static int licenseAge;
private string name;
private int age;
public Person(string name, int age) {
this.name = name;
this.age = age;
}
public void setLicenseAge(int age) {
licenseAge = age;
}
public string toString() {
string str = "";
str += "Name: " + name;
str += "\tAge: " + age + " (";
if (age < licenseAge)
str += “can not drive";
else
str += “can drive";
str += ")";
return str;
}
} // class Person
Person::licenseAge=0
Person::licenseAge=18
Person::licenseAge=21
שימוש במשתנה הסטטי
משתנה סטטי,
מאותחל ל- 0