为什么在java的主类中可以访问另一个类的非静态变量?

时间:2013-12-17 07:18:12

标签: java

这里我试图在main中访问Test类的非静态变量'a'。是    为什么?

  class Test{  
      public static void m1(){}  
      public void m2(){}  
      public int a=20;  
      public static int b=30;  

     public static void fun(){  
       System.out.println(a);  //it gives an error because variable a is non-static  
       System.out.println(b);  
     }  
   }  

   class Test1{  

     public static void main(String args[]){  
       Test s=new Test();  
       s.b=10;  
       s.a=20;  
       System.out.println(s.a); /*why this statement not giving an error even variable'a'is  
       non-static, we are accessing it in static main() method */  
     }  
   }  

8 个答案:

答案 0 :(得分:1)

您不能在静态方法中对实例变量使用非限定引用,因为这些引用隐式引用了不存在的this实例。当您指定s.a时,您具体指的是对象a的{​​{1}}字段,而不是某些不存在的s,因此Java会找到该字段并允许您访问它

答案 1 :(得分:1)

变量a是可访问的,因为它在Test类中是公共的,并且您可以从静态main方法访问它,因为您已经创建了一个名为s的Test实例。

答案 2 :(得分:0)

System.out.println(s.a);它不会出错,因为您正在创建测试类的对象并调用其变量

你可能会对在main方法中访问静态和非静态变量感到困惑(例如静态方法)。考虑这个

你可以直接写System.out.println(Test.b);,但你不能写System.out.println(Test.a);因为a不是静态的

答案 3 :(得分:0)

您正在创建Test(s对象)的实例并访问其公共属性。没关系。它应该这样工作。 访问此属性的“静态方式”如下所示:

int x = Test.a;

它不起作用,因为你的属性不是静态的。

答案 4 :(得分:0)

您正在通过实例(s)访问非静态变量,这是完全合法的,因为变量是公共的。静态或非静态与访问限制无关 - 唯一改变的是如果您需要一个实例来使用它。

答案 5 :(得分:0)

应该使用类实例对象访问非静态变量,这就是你所做的,这就是编译器没有抛出错误的原因。

实际上,b被错误地访问了(虽然它不会抛出错误,但会显示警告说静态变量应该以静态方式访问)。由于它是静态的,因此您需要使用类名来访问它。

Test.b = 20;

此外,您在fun()方法中收到错误,因为您试图在non-static上下文a内访问static字段fun() } 方法。即使main()static方法,您也可以使用a类的实例访问Test,这是正确的做法。

答案 6 :(得分:0)

我认为你是在混合非静态和私人。

访问非静态公共成员所需的只是持有该类的实例。

如果您不希望该成员可访问,请将其设为私有/受保护。

答案 7 :(得分:0)

您没有收到任何错误,因为您正在Test的实例上访问成员变量。例如:

public class Foo{
  private static int bar;
  private int foobar;

  public static void main(String[] args){
      System.out.println(bar); // possible,because bar is static
      System.out.println(foobar); // illegal since you're trying to access an instance variable from a static context
      System.out.println(new Foo().foobar); // possible since you're accessing the foobar variable on an instance of Foo