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
",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
",A.i);    //运行结果为:i = 10 
	}
}

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

class A
{
	private static void f()
	{
		System.out.printf("好哈哈哈哈
");
	}

}
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
");
		g();             //Error
	}
	
	public void g()
	{
		System.out.printf("GGGGGGG
");
	}
}

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
", A.getCnt());
		A aa1 = new A();
		System.out.printf("当前时刻A对象的个数:%d
", A.getCnt());
		A aa2 = new A();
		System.out.printf("当前时刻A对象的个数:%d
", 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
", aa2.i);    //结果为:99
		
		if (aa1 == aa2)
			System.out.printf("aa1 和 aa2相等
");     //运行结果为:aa1 和 aa2相等
		else
			System.out.printf("aa1 和 aa2不相等
");
	}
}




原文地址:https://www.cnblogs.com/yzy-blogs/p/5762655.html