先从一些简单的例子说起:
复制代码
上面这个程序说明了:类的多个对象共用一个static属性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class A { static int i = 10; public A() { } } public class TestStatic_1 { public static void main(String[] args) { A aa1 = new A(); A aa2 = new A(); aa1.i = 20; System.out.printf("aa2.i = %dn",aa2.i); //运行结果为:aa2.i = 20 } }
复制代码
上面程序说明了:static属性是属于类本身的,或者说,没有创建对象,我们依旧可以直接通过类名的方法访问该类内部的static属性。
1
2
3
4
5
6
7
8
9
10
11
12
13class A { public static int i = 10; } public class TestStatic_2 { public static void main(String[] args) { System.out.printf("i = %dn",A.i); //运行结果为:i = 10 } }
复制代码
上面程序说明了:只有非private的static成员才可以用过类名的方式访问。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16class A { private static void f() { System.out.printf("好哈哈哈哈n"); } } public class TestStatic_3 { public static void main(String[] args) { A.f(); //error } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class A { public int i = 10; public static void f() { System.out.printf("FFFFFFFn"); g(); //Error } public void g() { System.out.printf("GGGGGGGn"); } } public class TestStatic_4 { public static void main(String[] args) { A aa = new A(); aa.f(); } }
上面程序说明了:静态方法不能访问非静态成员,非静态方法可以访问静态成员。
上面通过四个简单的例子讲述了static的基本语法,下面通过两个例子讲述了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
27
28
29
30
31
32class A { private int i = 10; private static int cnt = 0; //cnt 为private和静态的,属于类本身,即使创建多个对象,也只有一个cnt,而且只能在构造函数内被修改 public A() { ++cnt; } public A(int i) { this.i = i; ++cnt; } public static int getCnt() //此处getCet应为静态的。属于类本身,通过类名的方式访问 { return cnt; //返回A对象的个数 } } public class StaticExample_1 { public static void main(String[] args) { System.out.printf("当前时刻A对象的个数:%dn", A.getCnt()); A aa1 = new A(); System.out.printf("当前时刻A对象的个数:%dn", A.getCnt()); A aa2 = new A(); System.out.printf("当前时刻A对象的个数:%dn", A.getCnt()); } }
最后一个例子说明如何保证一个类只能被创建一个对象
复制代码
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
30class A { public int i = 10; private static A aa = new A(); private A() //构造函数是private的,保证不能从类A外面new出A的对象 { } public static A getA() //必须是static的,因为如果是非静态的无法调用静态的成员aa { return aa; } } public class StaticExample_2 { public static void main(String[] args) { A aa1 = A.getA(); A aa2 = A.getA(); aa1.i = 99; System.out.printf("%dn", aa2.i); //结果为:99 if (aa1 == aa2) System.out.printf("aa1 和 aa2相等n"); //运行结果为:aa1 和 aa2相等 else System.out.printf("aa1 和 aa2不相等n"); } }
最后
以上就是神勇宝马最近收集整理的关于Java中static的用法的全部内容,更多相关Java中static内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复