• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static method related  RSS feed

 
N Sam
Ranch Hand
Posts: 77
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Book says static methods can not access object instance variables. But the following code successfully prints out
ba.balance = 10
instance var = 5
.

It seems like Static method is able to access the instance variable of another class, as well as the instance variable of main class. What gives ?


 
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
N Sam wrote:Book says static methods can not access object instance variables. But the following code successfully prints out
ba.balance = 10
instance var = 5
.

It seems like Static method is able to access the instance variable of another class, as well as the instance variable of main class. What gives ?



Static methods can't access instance variable via the this reference -- because it is in a static context. Where did you learn that it can't access any instance variables?

Henry
 
N Sam
Ranch Hand
Posts: 77
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is from the OCA exam book (by Mala Gupta) that i am reading, page 52:
"static methods aren't associated with objects and can't use any of the instance variables of a class".

But I suspect this is not true, based on my code. Static method is behaving just like regular method.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, classes don't have instance fields. Objects do. What you are doing is creating an object ba (or ip) and using that to access its fields.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A few minutes ago, I wrote:No, classes don't have instance fields. Objects do. . . .
That is not quite accurate.
 
N Sam
Ranch Hand
Posts: 77
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I will also post this question on the OCA forum and see if it elicits any answers. Question still remains open.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37507
552
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that is an English thing. This code is fine because it references the instance variable balance on the ba instance of BankAccount.



This code gives an error because a static method is trying to reference an instance variable and that isn't allowed.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!