【学习笔记】Static关键字
static 用来修饰属性和方法
属性:
静态的属性可以直接调用
package com.oop.demo06;
public class Student {
private static int age;
private String name;
public static void main(String[] args) {
Student.age = 10;
}
}
非静态的属性需要 实例化一个对象,在去调用
package com.oop.demo06;
public class Student {
private static int age;
private String name;
public static void main(String[] args) {
Student.age = 10;
Student student = new Student();
student.name = "zs";
}
}
静态和非静态的方法与属性相同
package com.oop.demo06;
public class Student {
public void run(){
}
public static void go(){
}
public static void main(String[] args) {
//静态
go();
//或者 Student.go();
//非静态
Student student = new Student();
student.run();
}
}
静态代码块
除了属性和方法有静态之外,还有静态代码块,他在类一创建就创建了,并且在构造方法之前,并且只执行一次
package com.oop.demo06;
public class Person {
{
System.out.println("匿名代码块");
}
static {
System.out.println("静态代码块");
}
public Person() {
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person = new Person();
}
}
我们可以看到程序先执行了静态代码块,然后是匿名代码块,最后是构造方法
我们在实例化一个对象
package com.oop.demo06;
public class Person {
public Person() {
System.out.println("构造方法");
}
{
System.out.println("匿名代码块");
}
static {
System.out.println("静态代码块");
}
public static void main(String[] args) {
Person person = new Person();
System.out.println("=================");
Person person1 = new Person();
}
}
可以看到静态代码块只执行1次
匿名代码块可以用来赋一些初始值
其他用法
我们如果想要调用Math类中的random方法,一般是这么写:
package com.oop.demo06;
public class Test {
public static void main(String[] args) {
double num = Math.random();
}
}
使用static,可以这样操作
package com.oop.demo06;
import static java.lang.Math.random;
public class Test {
public static void main(String[] args) {
double num = random();
}
}
这叫做静态导入包
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!