Why can I access a private variable from main method?

后端 未结 7 783
一整个雨季
一整个雨季 2020-12-06 06:24
package com.valami;

 public class Ferrari
 {
  private int v = 0;


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

  public Ferrari()
  {
   System         


        
相关标签:
7条回答
  • 2020-12-06 07:02

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

    e.g., 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.

    0 讨论(0)
  • 2020-12-06 07:06

    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.

    0 讨论(0)
  • 2020-12-06 07:08

    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.

    0 讨论(0)
  • 2020-12-06 07:10

    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.

    0 讨论(0)
  • 2020-12-06 07:15

    The main method is in the class Ferrari and thus can access private variables, even if it's static.

    0 讨论(0)
  • 2020-12-06 07:18

    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.

    0 讨论(0)
提交回复
热议问题