奇怪的问题

piaopiao11 2007-08-07 10:16:47
public class d {
public static void main(String[] args) throws IOException {
System.out.println(xxxx.test);
}
}

class xxxx{
public final static String test="abc";
static{
System.out.println("111");
}
}

为啥结果为:
abc
那个111怎么不打出来?????
...全文
258 17 打赏 收藏 转发到动态 举报
写回复
用AI写文章
17 条回复
切换为时间正序
请发表友善的回复…
发表回复
zdjray 2007-08-08
  • 打赏
  • 举报
回复
static 块只有在类被首次实例化的时候才会调用
这一点和静态常量不同~~
奋斗并快乐着 2007-08-08
  • 打赏
  • 举报
回复
mark
zangshulai 2007-08-07
  • 打赏
  • 举报
回复
学习
zephyr_cc 2007-08-07
  • 打赏
  • 举报
回复
支持下redduke1202(★及时结贴是一种美德★)
顺便补充点
这个问题涉及到类型(类或接口)主动使用和被动使用的问题
主动使用会导致类型初始化,而被动使用则不会
以下是6种类型主动使用的情况:

创建类的新实例
调用类的静态方法
使用类或接口的静态字段,或对其赋值(final static 除外, 原因如redduke1202所说)
调用API中某些反射方法
初始化该类的子类
虚拟机启动时被表明为启动类的类(含有main方法的那个类)
xvbtdavy 2007-08-07
  • 打赏
  • 举报
回复
学习中...
yankaga 2007-08-07
  • 打赏
  • 举报
回复
是因为你没有创建类的实例变量啊~大哥~
你如果在: public static void main(String[] args) throws IOException {
System.out.println(xxxx.test);
中间加一句XXXX A = NEW XXXX();
比如这样:
public static void main(String[] args) throws IOException {
xxxx a = new xxxx();
System.out.println(xxxx.test);
那个111就运行出来了~
「已注销」 2007-08-07
  • 打赏
  • 举报
回复
静态常量,分为2种
1种是编译期常量。比如 static final int,short,等基本类型及 String类型(直接赋值的)
另外一种是运行期常量 比如 static final long s=System.currentTimeMillis();
只有真正运行了才能确定下来

对于编译期常量,编译的时候就替换掉的,如果引用到,不会直接引起了ide载入
对于执行期常量,必须等初始化的时候才确定,如果引用到的话,就会引起类的载入和初始化
jihanzhong 2007-08-07
  • 打赏
  • 举报
回复
我个人的理解,原代码里程序没有涉及到类的加载,所以不会打印;

public final static String test=new String("abc"); 这里有个String,要加载类了,所以打印了。
piaopiao11 2007-08-07
  • 打赏
  • 举报
回复
不用把,static块里面的语句会在这个类装载的时候执行的。
chenyifei211 2007-08-07
  • 打赏
  • 举报
回复
你仅仅是引用class类的test变量值
并没有要求打印
如果你想打印的话可以用 Class class=new Class();
这样是把class类放入内存,故会打印
piaopiao11 2007-08-07
  • 打赏
  • 举报
回复

那public final static String test=new String("abc");
为什么有打呢?
jihanzhong 2007-08-07
  • 打赏
  • 举报
回复
xxxx.test 已经被等同于"abc"了。
不用load xxxx类
shujianhua 2007-08-07
  • 打赏
  • 举报
回复
同意,没有创建类的实例
或者
静态方法在内存中并未被程序的入口main方法调用
w058t 2007-08-07
  • 打赏
  • 举报
回复
支持,学习
malligator 2007-08-07
  • 打赏
  • 举报
回复
public class D {
public static void main(String[] args) throws IOException {
System.out.println(xxxx.test);
}
}

class xxxx {
public final static String test;
static {
System.out.println("111");
test="abc";
}
}
joejoe1991 2007-08-07
  • 打赏
  • 举报
回复
学习
grant999 2007-08-07
  • 打赏
  • 举报
回复
class xxxx{
xxxx(){
System.out.println(this.getClass().getClassLoader());
}
public final static String test="abc";
static{
System.out.println("111");
}

}

public class tt extends ClassLoader{

public static void main(String[] args)throws Exception {

new xxxx();
tt t=new tt();
System.out.println(t.findLoadedClass("xxxx"));//为什么总是返回null???
}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧