• Post Reply Bookmark Topic Watch Topic
  • New Topic

Protected variable class level  RSS feed

 
Stribor Kab
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have variable in class1 declared like this...



I also have method in class1 like this..



My class2 has something like this....



Which prints the balance. Why is it allowing me to print the balance even thought I made this filed protected?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Is class2 in the same package as class1?  Classes in the same package can access each other's protected variables.

Henry
 
Stribor Kab
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't have package statements at neither of the 2 files.  Both of the files are in same eclipse project directory
 
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
Stribor Kab wrote:I don't have package statements at neither of the 2 files.


If the two classes are in the default package, then they are in the same package, and hence, can access each other's protected fields.

Henry
 
Stribor Kab
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How are they in same package? Because they are in same directory?
 
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
Stribor Kab wrote:How are they in same package? Because they are in same directory?


No. It is not really directly related to the directory. They are in the same package, because both class don't have package statements. 

Henry
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stribor Kab wrote:I have variable in class1 declared like this...

. . .
Give all your variables private access. Only allow other code to access methods.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!