为什么一个对一个错呢?

飞行的兔子 2004-06-27 08:08:37
两个程序相似的用法!但出现不同的结果!
程序一:
class Bow1{
Bow1(int marker){
System.out.println("Bow1("+marker+")");

}
void f(int marker){
System.out.println("f("+marker+")");
}

}

class Table{
static Bow1 b1=new Bow1(1);
Table(){
System.out.println("Table()");
b2.f(1);
}
void f2(int marker){
System.out.println("f2("+marker+")");
}
static Bow1 b2=new Bow1(2);
}

class Cupboard{
Bow1 b3=new Bow1(3);
static Bow1 b4=new Bow1(4);
Cupboard(){
System.out.println("Cupboard()");

}
void f3(int marker){
System.out.println("f3("+marker+")");
}
static Bow1 b5=new Bow1(5);
}

public class StaticInitialization{
public static void main(String args[]){
System.out.println("Creating new Cupbaord() in main");
new Cupboard();
System.out.println(
"Creating new Cupboard() in main");
new Cupboard();
t2.f2(1);
t3.f3(1);
}
static Table t2=new Table();
static Cupboard t3=new Cupboard();
}

程序二:
class point{
float x;
float y;
point(float x,float y){
this.x=x;
this.y=y;
System.out.println("after ininizing x:"+this.x+"\ty:"+this.y);
}
}

public class TestThis extends point{
TestThis(float x,float y){
super(x,y);
System.out.println("class TestThis extends from point!");
}
public static void main(String args[]){
TestThis tt=new TestThis(2.0,3.0);
static point pt=new point(12.0,3.0);
tt.finalize();
pt.finalize();
}
}

程序一能顺利通过,而程序二却报错;
错误提示为:
TestThis.java;illegal start of expression
static point pt=new point(3.0,2.0)
...全文
104 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
飞行的兔子 2004-06-28
  • 打赏
  • 举报
回复
非常感谢楼上的两位!
skyboy0720 2004-06-28
  • 打赏
  • 举报
回复
我也明白了!
shuneng 2004-06-27
  • 打赏
  • 举报
回复
楼上说的对,static的变量只能作为类数据成员声明而不能在函数体中声明。
因为它是多个对象共有一份副本的。
sboom 2004-06-27
  • 打赏
  • 举报
回复
程序2
static 定义变量只能在函数外,函数内的变量不可能是static的。
另外 new point(3.0,2.0) 应该是 new point(3.0f,2.0f)
PageYi 2004-06-27
  • 打赏
  • 举报
回复
我发现第一个,可以把堆上产生的实例副给静态变量,这种类必须有一个静态属性
而第二个程序里面就没有静态属性
飞行的兔子 2004-06-27
  • 打赏
  • 举报
回复
怎么没有人回答啊!
skyboy0720 2004-06-27
  • 打赏
  • 举报
回复
学习!也帮你UP!
PageYi 2004-06-27
  • 打赏
  • 举报
回复
不太懂,帮你顶

62,614

社区成员

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

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