• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why can't I access instance variables from another class?  RSS feed

 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have two classes

User




and Team



why cant i go
System.out.println(Blackburn,teamStrength); or any of the other instance variables? after instantiating an object from Team in main?
 
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
jon ninpoja wrote:
why cant i go
System.out.println(Blackburn,teamStrength); or any of the other instance variables? after instantiating an object from Team in main?


First, I assume you mean "Blackburn.teamStrength" and not "Blackburn,teamStrength"?  ... but ... to answer your question, you declared the instance variable as "private", which means that it can't be accessed outside of the class.

Henry
 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi henry

i read that instance variables should always be private to keep in the spirit of encapsulation...
so what would be the right way to sort this out so i could access those variables to print change etc etc

 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry yes its . not , typo
 
Campbell Ritchie
Marshal
Posts: 56593
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
jon ninpoja wrote:. . . what would be the right way to sort this out so i could access those variables to print change etc etc

Via the methods of the object. You will need to write some methods.
 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so if i want to print out each of these i can make methods like
printTeamStrength and the methods in there will be able to access the private instance variables?

 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would be better to write a method that returns the value (these are called getters) instead of a method that prints the value.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!