• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why can I access "private instance variables" inside a main method.  RSS feed

 
siva kumar swamy yellapu
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am a beginner to java and currently exploring with access modifiers where I encountered the below scenario which is not obvious to me. The below code compiles fine, I don't understand why the statement in line 7 is correct. Can someone explain this.?

1. public class Foo {
2. private int a;
3.       private static int b;
4. public static void main(String[] args) {
5.                b = 2; // I understand that this statement is correct.
6. Foo foo = new Foo();
7.                foo.a = 1; // I totally don't have any idea of how this is correct.
8. }
9. }
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
siva kumar swamy yellapu wrote:I am a beginner to java and currently exploring with access modifiers where I encountered the below scenario which is not obvious to me. The below code compiles fine, I don't understand why the statement in line 7 is correct. Can someone explain this.?


Private variables are private to the class. This means that any instance of a class (or static methods) can access another instance (of the same class) private variables.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!