Many programmers, particularly when first introduced to Java, have problems with accessing member variables from their main method. The method signature for main is marked static - meaning that we don't need to create an instance of the class to invoke the main method. For example, a Java Virtual Machine (JVM) could call the class MyApplication like this :-
MyApplication.main ( command_line_args );
This means, however, that there isn't an instance of MyApplication - it doesn't have any member variables to access! Take for example the following application, which will generate a compiler error message.
public class StaticDemo
{
public String my_member_variable = "somedata";
public static void main (String args[])
{
// Access a non-static member from static method
System.out.println ("This generates a compiler error" +
my_member_variable );
}
}
If you want to access its member variables from a non-static method (like main), you must create an instance of the object. Here's a simple example of how to correctly write code to access non-static member variables, by first creating an instance of the object.
public class NonStaticDemo
{
public String my_member_variable = "somedata";
public static void main (String args[])
{
NonStaticDemo demo = new NonStaticDemo();
// Access member variable of demo
System.out.println ("This WON'T generate an error" +
demo.my_member_variable );
}
}
有这个习惯的,一般是从C语言过来的人,因为在C语言里面没有这么麻烦的东西,直接调用就行了,
但是Java是面向对象的。
类的静态成员函数是属于类的,不是对象的,也就是说即使对象不存在,它照样可以用,由于它不属于对象,
那么它就无法调用对象里面的静态函数。
关于static在C++的用法,大家可以参考下面这篇文章:
http://dev.csdn.net/article/19/article/20/20219.shtm
评论