A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 于潇 中级黑马   /  2012-4-24 09:46  /  2552 人查看  /  8 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

请看……

public class Shit {
  public int i=2;
  public static int j=3;
  public static void main(String[] args) {
    System.out.println(i);//有错
    System.out.println(j);
  }

}

怎样才能输出非静态的那个呢?

8 个回复

倒序浏览
static的方法只能访问静态成员(成员变量、成员函数)
因为static随着类的加载而加载
回复 使用道具 举报
静态方法不能访问非静态成员。
修改后的代码
public class Shit {
  public int i=2;
  public static int j=3;
  public static void main(String[] args) {
    System.out.println(new  Shit().i );//这样就不会有错了
    System.out.println(j);
  }

}
运行结果
2
3
回复 使用道具 举报
静态的表示是类所有的,直接用类就可访问,非静态的是对象所有的,必须创建出对象后再用对象去访问
回复 使用道具 举报
Friends★ 发表于 2012-4-24 09:58
静态方法不能访问非静态成员。
修改后的代码
public class Shit {

如果改为
Shit s = new Shit();
System.out.println(s.i);

这样可以么?
回复 使用道具 举报
类中非静态成员变量是在创建对象后才能调用的,需要创建对象后进行调用,代码如下;
public class Hello{
          public int i=2;
          public static int j=3;
          public static void main(String[] args){
                          Hello h=new Hello();
                          int n=h.i;
                         System.out.println(n);
                         System.out.println(j);
        }
}
回复 使用道具 举报
于潇 发表于 2012-4-24 10:01
如果改为
Shit s = new Shit();
System.out.println(s.i);

呵呵……可以的,和我那个是一个意思!只是我的那个是一步完成,你这种是分开来写的。

点评

谢谢!  发表于 2012-4-24 10:15
回复 使用道具 举报
public class Shit {
  public int i=2;
  public static int j=3;
  public static void main(String[] args) {
    System.out.println(i);//有错 楼主注意,int不是静态。主函数是静态的。所以静态不能直接访问非静态变量 i 的,可以改成静态或者创建对象调用
    System.out.println(j);
  }
}
回复 使用道具 举报
彭威 中级黑马 2012-4-24 13:10:50
9#
你的 i 属于shit类里面的 非静态成员, 要想调用的话必须建立一个对象;才能用
可以这样:
public class Shit
{
  public int i=2;
  public static int j=3;
  public static void main(String[] args)
{
    System.out.println(new  Shit().i );
    System.out.println(j);
  }
}
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马