Why can I access a private variable from main method?

后端 未结 7 833
一整个雨季
一整个雨季 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.

提交回复
热议问题