java静态修饰符static基础
# static变量
- 使用static修饰的字段我们称之为静态字段,又被称为类变量
- 此时这个静态变量属于当前类,当前类的所有实例都可以通过类名,访问到当前静态变量
- 静态变量在内存当中只存储一份
class User {
public String username;
// 静态字段 cardId
public static int cardId;
}
1
2
3
4
5
6
2
3
4
5
6
# 通过实例修改静态变量
public class User {
public String username;
// 静态字段 cardId
public static int cardId;
public User(String username) {
this.name = name;
}
public static void setCardId(int value) {
cardId = value;
}
}
public class TestStatic {
public static void main(String[] args) {
Admin lewyon1 = new Admin("lewyon1");
Admin lewyon2 = new Admin("lewyon2");
lewyon1.cardId = 88;
System.out.println(lewyon1.cardId); // 88
System.out.println(lewyon2.cardId); // 88
Admin.setCardId(199);
System.out.println(Admin.cardId); // 199
System.out.println(lewyon1.cardId); // 199
System.out.println(lewyon2.cardId); // 199
}
}
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
31
32
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
31
32
- 通过执行结果我们可以知道,实例在修改静态变量的时候,所有实例的静态变量都会发生更改
- 因此所有的实例都是共享同一份静态变量
# 静态方法
使用static修饰的方法我们称为静态方法
最常见的静态方法应该是我们编写的main方法
public static void main(String[] args) {
System.out.println("static--------");
}
1
2
3
4
5
2
3
4
5
# 静态方法特性
public abstract class testClass {
public static void testFunc(){
}
public abstract static void testFunc2(); // Illegal combination of modifiers: 'abstract' and 'static'
}
public class TestClass2 {
private int user;
private static int cardId;
public static void func1(){
int card1 = cardId;
// int user1 = user; // Non-static field 'user' cannot be referenced from a static context
// int user2 = this.user; // 'TestClass2.this' cannot be referenced from a static context
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
从上面的静态方法我们可以知道
static静态方法不依赖于任何实例,因此当类加载的时候,静态方法static已经存在
静态方法不能是抽象方法,需要对静态方法进行实现。
静态修饰符statix只能访问所属类的静态字段和静态方法,方法中不能有 this 和 super 关键字。
# 总结
- 以上就是java中static修饰符的基础使用和了解
- static修饰符常用在工具类的编写当中,类似Arrays的方法扩展等。
- static只能访问所属类的静态字段和方法,并且在方法中不能用this以及super关键字
- 静态方法不能是抽象方法,需要对静态方法进行实现。
欢迎关注公众号:程序员布欧,不定期更新技术入门文章
创作不易,转载请注明出处和作者。
- 01
- spring boot集成redis基础入门10-07
- 02
- spring boot使用swagger生成api接口文档10-07
- 03
- spring boot项目使用mybatisplus代码生成实例08-18