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

提问JAVA函数调用的问题
小弟初学JAVA,想不明白一个问题,为什么在类中调用函数一定要静态地调用?
代码如下:
为什么不可以像C++里面那样直接调用呢?
望大侠不甚赐教!

public   class   ghost   {
  public static   void     ghost()
{
System.out.println( "函数调用成功!!! ");

}

public   static   void   main(String   args[]   )
{
System.out.println( "ghost   is   a   big   worry ");
for(int   a=0;a <10;a++)
{
ghost();

}


}

}


------解决方案--------------------
没有什么一定要静态调用的说法。之所以像楼主这么写,只是用起来方便罢了。完全可以改成这样:

public class Ghost {

public void shout() { //这个方法不是静态的
System.out.println( "函数调用成功!!! ");
}

public static void main(String args[] ) {
System.out.println( "ghost is a big worry ");

for(int a=0;a <10;a++) {
new Ghost().shout();
}
}
}
------解决方案--------------------
这就是面想对象的优点。
比如调用System.out.println()
还有Math.cos()等函数的调用。
静态方法可以直接用类然后.方法调用。
以后多编程就自然清楚了。