在网上找到一个连接数据库的文章里面有下面这段程序:
public class DBPool {
private static DataSource pool;
static {
Context env = null;
try {
env = (Context) new InitialContext().lookup("java:comp/env");
pool = (DataSource) env.lookup("jdbc/DBPool");
}
public static DataSource getPool() {
return pool;
}
}书里说static块中的内容仅在生成该对象或初次访问该静态数据成员时会被执行,如果程序中有多个类,每个类中都使用getPool()方法,static中的语句还会被执行一次吗。
public class DBPool {
private static DataSource pool;
static {
Context env = null;
try {
env = (Context) new InitialContext().lookup("java:comp/env");
pool = (DataSource) env.lookup("jdbc/DBPool");
}
public static DataSource getPool() {
return pool;
}
}书里说static块中的内容仅在生成该对象或初次访问该静态数据成员时会被执行,如果程序中有多个类,每个类中都使用getPool()方法,static中的语句还会被执行一次吗。
class A{
static {
System.out.println("dkddddk");
}
static void prt(){
}
}
class B{
public void prt(){
A.prt();
}
}
class C{
public void prt(){
A.prt();
}
}
public class Test{ public static void main(String[] args){
new B().prt();
new C().prt();
}
}
{
static { System.out.println("staticA");}
A()
{
System.out.println("A");
}
}
class B
{
public static void main(String []args)
{
new A();
new A();
}
}static 块只执行一次...........