static的一个问题.

SimerJoe 2007-12-21 02:14:56
static方法,static变量见得多了.今天看见一个

public class classname()
{
static
{
//static直接跟{},{}里面写代码.
code......
}
}

这个是什么意思呀?这些代码算静态的还是算对象的?
...全文
143 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
1.运行一个程序,你至少要开辟一块静态内存
2.不需要创建对象,就要访问某个方法

而static就是这样一个关键字,声明了static后就表示上述两个目的
oo7oo7 2008-02-16
  • 打赏
  • 举报
回复
今天看课本有这个内容,这个写法是 static代码块,是一个知识点.具体用法可以搜一下 static代码块.
zenny_chen 2007-12-22
  • 打赏
  • 举报
回复
静态块在类被加载时执行一次。也就是说,即使没有用该类创建任何对象,只要它被虚拟机加载,那么静态块就会被执行。这个和所有类静态变量的初始化一样,都在类被加载时调用。

我们可以看以下代码:


class StaticTest {

public static int h = 100;

private int p;

static {
System.out.println("The static varaible is: " + h);
}

public static void incDisplay() {
System.out.println("Now, the static answer is: " + ++h);
}

public StaticTest() {
p = 10;
}

public void objectDisplay() {
System.out.println("The answer is: " + p);
}
}



public class Test {

public static void main(String[] args) {

StaticTest.incDisplay();
StaticTest.incDisplay();

StaticTest test = new StaticTest();

test.objectDisplay();
}
}

liujun999999 2007-12-22
  • 打赏
  • 举报
回复
为什么我的回复出不来
liujun999999 2007-12-22
  • 打赏
  • 举报
回复
静态初始化块,在class被导入的时候调用,只调用一次
另外还有一个没有static的东西,叫初始化块,在构造之前调用

class A{
A(){
System.out.println("构造A");
}
{
System.out.println("构造前调用")
}
}
emperor_java 2007-12-22
  • 打赏
  • 举报
回复
一般是调用本地库的时候这么用.
  • 打赏
  • 举报
回复
打错字了,“大多”应为“大说”.
  • 打赏
  • 举报
回复
大多半天都有可能不明白,实践乃是检验真理的唯一标准,测试一下下面的代码,你就会明白了

[size=30px]o(∩_∩)o[/size]

public class Test {
public static void main(String[] args) {
Test1 t1a = new Test1();
Test1 t1b = new Test1();

Test2 t2a = new Test2();
Test2 t2b = new Test2();
}
}


public class Test1 {
static {
System.out.println("I am a static block.");
}
}


public class Test2 {
{
System.out.println("I am not a static block.");
}
}
老紫竹 2007-12-21
  • 打赏
  • 举报
回复
用于类自身需要某些初始化工作。
比如:初始化那些static 的变量,这些变量在那些static method里面需要使用!并且那些变量需要很多的步骤才能完成,一般采用如下方法比较好

static {
initClass();
}
static void initClass(){
....
}
fastso 2007-12-21
  • 打赏
  • 举报
回复
不是很喜欢这样的写法。。
godfather134 2007-12-21
  • 打赏
  • 举报
回复
静态块!
shili150 2007-12-21
  • 打赏
  • 举报
回复
当然算静态的
healer_kx 2007-12-21
  • 打赏
  • 举报
回复
Java一般叫static的为类的。。。区别于对象的。

代码在类对象构造前会被执行一次。很不错的设计。

62,614

社区成员

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

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