Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...