繁体   English   中英

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

[英]why non-static variable of another class is accessible in main class in 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 */  
     }  
   }  

您不能在静态方法中使用对实例变量的非限定引用,因为它们隐式引用不存在的this实例。 当你指定sa ,你具体指到a对象的领域s ,而不是某些不存在的this ,所以Java发现场,让你访问它。

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

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

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

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

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

int x = Test.a;

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

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

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

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

Test.b = 20;

此外,你在错误fun()方法,因为你试图访问一个non-statica一个内部的static背景下这是fun()方法。 尽管main()是一个static方法,你访问a使用的实例, Test类,这是做正确的事。

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

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

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

您没有收到任何错误,因为您正在访问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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM