Why can I access a private variable from main method?

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

提交回复
热议问题