非要将创建对象的声明写到main的方法中么?

来源:百度知道 编辑:UC知道 时间:2024/05/10 20:59:42
1、程序报错
class a
{
a A=new a();
a() {
}
void c() {
}
}
class b
{ b test = new b();//这是初始创建的对象
a B;
void f()
{ B.c();
}
public static void main(String[] args)
{
test.f();
}
}
2这是正确的
class a
{
a A=new a();
a() {
}
void c() {
}
}
class b
{
a B;
void f()
{ B.c();
}
public static void main(String[] args)
{b test = new b();
test.f();
}
}

非要将b test = new b();放到main方法中声明test.f();这个方法才能在main方法中调用么?我如果只想象1中那样在初始创建然后在main中调用test.f();方法我该怎么去做呢?

也可以在其它方法中创建对象
但是必须写在方法中,方法外是不能创建的

这是做不到的!! 因为静态方法不可以访问非静态变量的!

除非将b类中的f()方法改为静态的,在main()方法里直接调用,或者在构造方法里调用非静态的f()方法!

可以不过没有那个必要
但是你真想那样做可以在第一个程序
b test = new b();//这是初始创建的对象
改为
static b test = new b(); //这是初始创建的对象
只加个修饰 static

反对赌东道赌东道法