简体   繁体   中英

Why can I access a private variable from main method?

package com.valami;

 public class Ferrari
 {
  private int v = 0;


  private void alam()
  {
   System.out.println("alam");
  }

  public Ferrari()
  {
   System.out.println(v);
  }



  public static void main(String[] args)
  {
   Ferrari f = new Ferrari();
   f.v = 5;
   System.out.println(f.v);
  }

 }

Hi all! I have one simple question.... WHY can I reach a private variable from the main method ? I know, I'm in the containing class, but it is main. I believed the main is NOT part of the class which is containing it... Then I would not to reach an private member, but I can....WHY? Please help...thx

Classes can access the private instance variables of (other) objects of the same type.

The following is also possible

public class Foo {

    private int a;

    public void mutateOtherInstance(Foo otherFoo) {
        otherFoo.a = 1;
    }
}

You could argue if this is desirably or not, but it's just a rule of life that the JLS has specified this is legal.

Main is a part of you class, you have declared it inside your class :) What main is not is part of your object, it will not be any part of the objects you create from the class but it is still part of the class. This is correct for any static function as main is just a normal static function that the framework knows it should look for when the program is executed.

main方法在类Ferrari ,因此可以访问私有变量,即使它是静态的。

Well, main() is part of the containing class. In fact, main() is exactly like every other method, except that you can start the JVM and tell it to run the main() method of a class from the command line.

As long as the private variable is in the same class as the main() method, then the main() method has access to it. In general, even static methods have access to private fields of instances of the same class.

The only special feature of the main method is it is used to tell the compiler where program execution should begin. Other than that it behaves just like any other class method and has access to private variables like any other class method.

Because main is static and your class hasn't been instantiated.

eg, you have no Ferrari object to access. You must create a Ferrari object then access it's members. static main is a special static function. You can think of it as sort of separate if you want. So if you moved your main method outside of Ferrari you would expect that you would have to create an instance of Ferrari to use it... same deal here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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