static关键字详解
static关键字详解
静态变量对于类,所有对象(实例)所共享,当直接使用类去调用得到说明这个这个变量是静态
(静态属性)
package com.oop.demo07;
public class Student {
private static int age;//静态变量
private double score;//非静态变量
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(Student.age);//如果是静态变量,直接用类名去.变量
//System.out.println(Student.score);错误:非静态的字段不能这样使用
System.out.println(s1.score);
System.out.println(s1.age);
}
}
package com.oop.demo07;
public class Person {
//2:赋初值~
{
System.out.println("匿名代码块");
}
//1:只执行一次
static{
System.out.println("静态代码块");
}
//3:
public Person(){
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person = new Person();
System.out.println("====================");
Person person2 = new Person();
}
}



浙公网安备 33010602011771号