static关键字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class Student { private static int age; private double score; public void run(){ go(); //非静态方法可以调用静态方法 } public static void go(){ //run(); //static方法是和类一起加载的,加载时,run()还没加载,所以不能直接调用 } public static void main(String[] args) { Student s1 = new Student(); System.out.println(Student.age); //System.out.println(Student.score); System.out.println(s1.age); System.out.println(s1.score); ( new Student()).run(); //static方法是和类一起加载的,加载时,run()还没加载,所以不能直接调用,只能通过new来调用 go(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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 person1 = new Person(); System.out.println( "================" ); Person person2 = new Person(); } } /* 静态代码块 匿名代码块 构造方法 ================ 匿名代码块 构造方法 */ |
增加知识点
1 //静态导入包
2 import static java.lang.Math.random;
3 import static java.lang.Math.PI;
4
5 public class Test {
6 public static void main(String[] args) {
7 System.out.println(random());
8 System.out.println(PI);
9 }
10 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结