static关键字----->单例模式

来源:互联网 发布:数据铁笼的概念 编辑:程序博客网 时间:2024/06/05 16:37
static关键字:静态的 在对象创建前就加载到内存

用法:用在属性和方法的前面


一,用在属性前面
public class A{
int i;
static int   j;
public A(){
i++;
j++;
System.out.println("i="+i);;
System.out.println("j="+j);;
}
}
测试:
A a  = new A(); i = 1 j = 1

A b = new A(); i = 1  j = 2


二,用在方法前面
静态的方法是在new对象之前就被加载到内存中了:
而非静态方法是new出对象之后才被加载到内存中。

总结:静态的不能调用非静态的。


三,单列模式:
一个类默认情况下是可以new出无数个对象
单列模式是指:一个类只能new出一个对象

public class Human {
//1,饿汉式
/*private static Human human ;
//1,将构造方法私有
private Human(){}
public static Human getHuman(){
if(human==null)
human = new Human();
return human;
}


//2,懒汉式
private static Human human = new Human();
private Human(){};
public static Human getHuman(){
return human;
}

饿汉式比懒汉式要好,懒汉式没调用就创建对象在内存中。
}


阅读全文
0 0