带你了解Java中Static关键字的用法
作者:MMorant 时间:2021-11-07 15:04:32
Java中Static关键字的一些用法详解
1. Static 修饰类属性,因为静态成员变量可以通过类名+属性名调用,非静态成员变量不能通过类名+属性名调用;
public class Student {
private static int number;//静态变量
private String name;//非静态变量
public static void main(String[] args) {
System.out.println(Student.number);
System.out.println(Student.name);//会报错 因为非静态成员变量不能通过类名+属性名调用
}
}
2. Static 修饰类方法,可以通过类名.静态方法名的方式调用静态方法,不可以用类名.静态方法名调用非静态方法;
public class Student {
public static void go(){};//静态方法
public void run(){};//非静态方法
public static void main(String[] args) {
Student.go();//可以用类名.静态方法名的方式调用静态方法
Student.run();//报错,不可以用类名.静态方法名调用非静态方法
}
}
3. 静态代码块,匿名代码块,构造函数。三者的调用顺序为(静态代码块(只调用1次) --> 匿名代码块 --> 构造函数)。
public class Student {
//匿名代码块,每创建一个student对象就会调用一次匿名代码块
{
System.out.println("调用匿名代码块");
}
//静态代码块,和类加载一起发生,只会调用一次
static {
System.out.println("调用静态代码块");
}
//构造函数,每创建一个student对象就会调用一次该方法
public Student() {
System.out.println("调用构造函数");
}
public static void main(String[] args) {
new Student();
new Student();
}
}
【第三点 测试结果】
来源:https://blog.csdn.net/qq_52979994/article/details/119743103
标签:Java,Static
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java编程之基于SpringBoot框架实现扫码登录
2023-02-14 02:39:28
![](https://img.aspxhome.com/file/2023/9/62999_0s.png)
Java文件操作之按行读取文件和遍历目录的方法
2023-11-24 16:58:21
kafka并发写大消息异常TimeoutException排查记录
2023-11-27 23:07:11
![](https://img.aspxhome.com/file/2023/8/60368_0s.png)
java 实现迷宫回溯算法示例详解
2023-12-14 23:52:26
![](https://img.aspxhome.com/file/2023/2/62982_0s.png)
Flutter 剪裁组件的使用
2023-06-18 13:15:04
![](https://img.aspxhome.com/file/2023/3/96783_0s.png)
详解基于spring多数据源动态调用及其事务处理
2023-06-23 14:37:25
![](https://img.aspxhome.com/file/2023/0/57530_0s.png)
SpringMVC记录我遇到的坑_AOP注解无效,切面不执行的解决
2021-08-09 06:20:58
Java中BigDecimal类的使用详解
2021-12-13 05:30:52
![](https://img.aspxhome.com/file/2023/0/62770_0s.png)
Hibernate双向多对多映射关系配置代码实例
2022-12-26 22:30:30
SpringMVC的执行过程浅析
2021-05-31 20:51:11
![](https://img.aspxhome.com/file/2023/4/62074_0s.png)
Java中的InputStreamReader和OutputStreamWriter源码分析_动力节点Java学院整理
2022-10-13 10:46:53
![](https://img.aspxhome.com/file/2023/5/62045_0s.png)
理解java设计模式之建造者模式
2023-03-13 14:48:55
详解Spring全局异常处理的三种方式
2023-11-11 15:31:47
java通过方向键控制小球移动的小游戏
2023-11-10 05:25:59
springboot搭建访客管理系统的实现示例
2023-09-02 13:10:41
![](https://img.aspxhome.com/file/2023/3/58463_0s.png)
Spring bean的实例化和IOC依赖注入详解
2023-11-23 23:57:15
SpringBoot使用Mybatis&Mybatis-plus文件映射配置方法
2023-05-16 12:53:02
详解spring boot引入外部jar包的坑
2021-07-29 10:49:49
![](https://img.aspxhome.com/file/2023/4/61314_0s.jpg)
如何用Java Stream写出既高雅又装*的代码
2022-04-13 23:23:58
![](https://img.aspxhome.com/file/2023/6/65736_0s.jpg)
Java技能点之SimpleDateFormat进行日期格式化问题
2023-09-09 01:50:26
![](https://img.aspxhome.com/file/2023/9/58339_0s.jpg)