日期:2014-05-20  浏览次数:20759 次

这些为什么都不行呢?请教
1
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();//这是初始创建的对象
b   n;                               //
n.f();                           //这样为什么不行
      }
    }
2
class   a  
{  
a   A=new   a();  
a()   {  
}  
void   c()   {  
}  
}
  class   b  
{
  void   f()  
{   a   B;     //这样也不行
  B.c();  
              }  
public   static   void   main(String[]   args)
                           
{   b     =   new   b();
  test.f();                          
      }
    }
3
class   a  
{  
a()   {  
      }  
void   c()   {  
        }  
}
  class   b  
{
  void   f()  
{   a   A=new   a();
    a   B;     //这样还不行
  B.c();  
              }  
public   static   void   main(String[]   args)
                           
{   b     =   new   b();
  test.f();                          
      }
    }
反正以上都是报错
只有把a   的引用放到所有的方法之外   非静态的方法才能用对象的引用去调用方法
在静态的方法中还不能建立个引用去调用方法   只能是用   创建的对象去调用这又是为什么?为什么非静态的就能用引用去调用方法呢?而且引用一定要在个方法之外呢?



------解决方案--------------------
晕,看得头晕晕的
看得进度和你差不多,试着回答你一下问题,不知道对不对
第一个问题
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();//这是初始创建的对象
b n; //
n.f(); //这样为什么不行 在静态方法中调用实例方法,必须要创建一个对象能调用,而你这里之是申明了一个变量,所以错误。
}
}
------解决方案--------------------
第一个问题,n没有初始化,也就无法调用方法f();而class b 中的B是类成员,程序自动初始化;
第二个问题,和上面的差不多,B不属于类成员了,也就是说没法自动初始化造成;
第三个问题,和第二个问题一样