注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

TOTO

Think and Be Different

 
 
 

日志

 
 

Accessing non-static member variables from static methods (such as main)  

2007-03-19 21:52:35|  分类: 默认分类 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

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
  评论这张
 
阅读(244)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017