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 );
}
}
Subscribe to:
Post Comments (Atom)
Man Utd's next generation of wonderkids
Manchester United have set off on their pre-season United States tour with a number of young stars involved, but some other talents have lef...

-
I forget to post this farewell photo for so around one week liao. Last wednesday 30th April 2008 is my f@rewell at Vida Sprint Sdn Bhd. So ...
-
My Team have won the best dressed Halloween competition for my company Halloween Annual Dinner last friday (2009-01-09). The winner prize is...
-
Oracle Java on Windows: C:\ProgramData\Oracle\Java\javapath I recently downloaded an early access release of JDK 9 ( build 68 ) fo...
2 comments:
good tips for duke beginner :)
haha.
Post a Comment