【问题标题】:java class why public static void main(String[] args) method can not access the property value of the class it is in?java类为什么public static void main(String[] args)方法不能访问它所在类的属性值?
【发布时间】:2014-08-11 16:08:04
【问题描述】:
public class Name{
int b = 100;
public void get(){
    System.out.println(b);
}

public int num(){
    return b;
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println(b);
}

}

get 方法可以访问 b,num 方法也可以访问 b。为什么 public static void main 方法不能访问 b。

【问题讨论】:

  • 静态方法只能访问静态属性。

标签: java class methods


【解决方案1】:

因为b 是一个实例字段,其范围在Name 类的实例中。

您的main 方法是static,作用于类本身。

b 声明为static,以便能够从main 方法访问它。

您还需要创建方法 get()num() static 进行编译。

【讨论】:

    【解决方案2】:

    这是一个实例(非静态)字段,所以你需要一个实例来引用它:

    public static void main(String[] args) {
        System.out.println(new Name().b);
    }
    

    【讨论】:

      【解决方案3】:

      静态方法只能访问静态属性。您可以将 b 设为静态,也可以将 Name 实例化:

      public class Name{
      int b = 100;
      
      public void get(){
          System.out.println(b);
      }
      
      public int num(){
          return b;
      }
      
      public static void main(String[] args) {
          new Name(args);
      }
      
      public Name(String[] args) {
          System.out.println(b);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-22
        • 1970-01-01
        • 2019-06-15
        • 2011-12-10
        • 1970-01-01
        • 2019-11-23
        • 2018-11-12
        • 1970-01-01
        相关资源
        最近更新 更多