class Student {
public String name;
public int age;
public static String classRoom="教学楼602";
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student("张三",21);
}
}
通过调试得到初始化对象我们并没有得到classRoom的值是因为静态变量属于类而不是类的某个对象。这就意味着无论创建了多少个对象,静态变量只有一份。
那我们应该怎么访问呢?
我们可以通过对象访问但是这种不推荐因为不合理。
所以我们一般通过类名访问
我们再看下面的代码
public class Test {
public static int count =100;
public static int func(){
Test test = new Test();
test.count++;
test.count++;
test.count--;
Test.count++;
return count;
}
public static void main(String[] args) {
System.out.println(func());
}
}
会输出102 因为静态变量只有一份
所以被static修饰的变量有以下特性
1. 当一个变量被声明为static时,它就成为了一个静态变量。静态变量属于类而不是类的某个对象。这就意味着无论创建了多少个对象,静态变量只有一份。
2. 既可以通过对象访问,也可以通过类名访问,但一般更推荐使用类名访问
3. 静态变量存储在方法区
4. 生命周期伴随类的一生(即:随类的加载而创建,随类的卸载而销毁)
public class StaticMethodExample {
public static void iPrint(){
System.out.println("静态方法");
}
public static void main(String[] args) {
StaticMethodExample.iPrint();
}
}
静态方法也属于类而不是对象,可以直接通过类名调用,无需创建变量。
我们也可以通过静态方法来访问静态成员变量
class Student1 {
private static String classRoom = "教学楼602";
public static String getClassRoom(){
return classRoom;
}
}
public class Main {
public static void main(String[] args) {
Student1 student1 = new Student1();
System.out.println(student1.getClassRoom());
}
}
静态方法的特点
1. 不属于某个具体的对象,是类方法
2. 可以通过对象调用,也可以通过类名.静态方法名(...)方式调用,更推荐使用后者
3. 不能在静态方法中访问任何非静态成员变量
// 编译失败:无法从 static 上下文引用非 static 字段 'age'
4. 静态方法中不能调用任何非静态方法,因为非静态方法有this参数,在静态方法中调用时候无法传递this引用
1. 节省内存:因为静态变量和方法只有一份,无需为每个对象都创建一份。
2. 方便共享数据和方法:无需创建对象即可访问
static关键字为 Java 编程提供了更多的灵活性和便利性,但在使用时需要谨慎考虑其适用场景和影响。
普通代码块:定义在方法中的代码块
public class Main {
public static void main(String[] args) {
{//直接使用{}定义,普通方法块
int a=10;
a++;
System.out.println(a);
}
}
}
构造块:定义在类中的代码块(不加修饰符)。也叫:实例代码块。构造代码块一般用于初始化实例成员变量。
class Car{
private String name;
private double price;
{
this.name="宝马";
this.price=99999.9;
System.out.println("构造代码块");
}
public void show(){
System.out.println(this.name+" "+this.price);
}
}
public class Demo {
public static void main(String[] args) {
Car car = new Car();
car.show();
}
}
运行结果:
使用static定义的代码块称为静态代码块。一般用于初始化静态成员变量。
class Car{
private String name;
private double price;
private static int tiresNumber;
public Car(){
System.out.println("无参构造函数");
}
static {//静态代码块
tiresNumber=4;
System.out.println("静态代码块");
}
{//实例代码块
this.name="宝马";
this.price=99999.9;
System.out.println("构造代码块");
}
}
public class Demo {
public static void main(String[] args) {
Car car = new Car();
}
}
执行顺序静态的代码块>构造代码块>构造方法 当是同一级的时候执行顺序和书写顺序有关系
静态代码块只会执行一次
1.静态代码块不管生成多少个对象,其只会执行一次
2.静态成员变量是类的属性,因此是在JVM加载类时开辟空间并初始化的
3.如果一个类中包含多个静态代码块,在编译代码时,编译器会按照定义的先后次序依次执行(合并)
4.实例代码块只有在创建对象时才会执行
因篇幅问题不能全部显示,请点此查看更多更全内容