/**
*
*/
package com.test.mysql;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
* @filename Main.java
* @author code by jianghuiwen
* @mail [email protected]
*
*/
class Test
{
String name;
}
class Person
{
//static仅仅在类被初始化的时候,被初始化一次
private static Test test=new Test();
public Test gettest()
{
return test;
}
}
public class Main {
/**
* @param args
*/
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Test test=new Person().gettest();
Test test1=new Person().gettest();
System.out.println(test);
System.out.println(test1);
}
}
所以两次输出的对象是同一个对象。
但是,如果用这样的方法:
/**
*
*/
package com.test.mysql;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
* @filename Main.java
* @author code by jianghuiwen
* @mail [email protected]
*
*/
class Test
{
String name;
}
class Person
{
//static仅仅在类被初始化的时候,被初始化一次
private static Test test;
public Test gettest()
{
//每次都会返回一个不同的引用,导致static两次的地址是不同的
test=new Test();
return test;
}
}
public class Main {
/**
* @param args
*/
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Test test=new Person().gettest();
Test test1=new Person().gettest();
System.out.println(test);
System.out.println(test1);
}
}