static int java_Java中static的用法

先从一些简单的例子说起:

class 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 = %d\n",aa2.i); //运行结果为:aa2.i = 20

}

}

上面这个程序说明了:类的多个对象共用一个static属性。

class A

{

public static int i = 10;

}

public class TestStatic_2

{

public static void main(String[] args)

{

System.out.printf("i = %d\n",A.i); //运行结果为:i = 10

}

}

上面程序说明了:static属性是属于类本身的,或者说,没有创建对象,我们依旧可以直接通过类名的方法访问该类内部的static属性。

class A

{

private static void f()

{

System.out.printf("好哈哈哈哈\n");

}

}

public class TestStatic_3

{

public static void main(String[] args)

{

A.f(); //error

}

}

上面程序说明了:只有非private的static成员才可以用过类名的方式访问。

class A

{

public int i = 10;

public static void f()

{

System.out.printf("FFFFFFF\n");

g(); //Error

}

public void g()

{

System.out.printf("GGGGGGG\n");

}

}

public class TestStatic_4

{

public static void main(String[] args)

{

A aa = new A();

aa.f();

}

}

上面程序说明了:静态方法不能访问非静态成员,非静态方法可以访问静态成员。

上面通过四个简单的例子讲述了static的基本语法,下面通过两个例子讲述了static的实际的应用。

下面这个程序计算一个类被创建对象的个数:

class 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对象的个数:%d\n", A.getCnt());

A aa1 = new A();

System.out.printf("当前时刻A对象的个数:%d\n", A.getCnt());

A aa2 = new A();

System.out.printf("当前时刻A对象的个数:%d\n", A.getCnt());

}

}

最后一个例子说明如何保证一个类只能被创建一个对象

class 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("%d\n", aa2.i); //结果为:99

if (aa1 == aa2)

System.out.printf("aa1 和 aa2相等\n"); //运行结果为:aa1 和 aa2相等

else

System.out.printf("aa1 和 aa2不相等\n");

}

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值