在定义一个类时,只是在描述某事物的特征和行为,并没有产生具体的数据。只有通过new关键字创建该类的实例对象时,才会开辟栈内存和对内存,在堆内存中每个对象会有自己的属性。如果希望某些属性被所有对象共享,就必须将其声明为static属性。如果属性使用了static关键字进行修饰,则该属性可以直接用类名称进行调用。除了修饰属性,static关键字还可以修饰成员方法。
static一般称之为“静态的”。所以也会有“非静态的”,也就是不加static时。
public class Student {
private String name; //定义name属性
private int age; //定义age属性
private String school = "加州大学";//定义school属性
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
this.school = school;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school='" + school + '\'' +
'}';
}
}
class StudentTest{
public static void main(String[] args) {
Student s1 = new Student("张三",20);//实例化对象Student
Student s2= new Student("李四",20);//实例化对象Student
System.out.println(s1.toString());//输出
System.out.println(s2.toString());//输出
}
}
上面是不用static时的情况,school属性随对象创建而创建,假如一个学校有100个人,是不是每个人都需要在单独创建一次学校属性呢?那样是不是太麻烦了啊!此时我们就会为了此类问题,可以使用static关键字修饰school属性,将其变为公共属性,在堆空间中单独开辟一块内存空间,被Student类的所有对象共享。同时可以通过类直接调用。
public class Student {
private String name; //定义name属性
private int age; //定义age属性
private static String school = "加州大学";//定义school属性为静态
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
this.school = school;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static String getSchool() {
return school;
}
public static void setSchool(String school) {
Student.school = school;
}
}
class StudentTest{
public static void main(String[] args) {
Student s1 = new Student("张三",20);
Student s2= new Student("李四",20);
System.out.println(Student.getSchool());//直接用类调用静态方法,
System.out.println(s1.toString());
System.out.println(s2.toString());
}
}