Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Visibility of changes to an object's variables?

 
Jasper Vader
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
an explanation for a question at examulator had this quote - "If an object is passed to a method, changes to its variables will be valid wherever the class is visible." ... but there are situations aren't there, where a change is not visible? if the object is passed to the method, but the change is made to the variable not via the "." way of refering to it?
so in the following code snippet, in the deduct() method, the reference to balance is via a.balance .... and the change is visible later, but if the reference to balance variable was just "balance" and not "a.balance", the change would NOT be visible outside the deduct() method?
public void Go(){
Account personal = new Account();
personal.rate=7;
Account business = new Account();
business.rate =5;
deduct(business);
System.out.println(business.balance);
System.out.println(personal.rate);
}
public void deduct(Account a){
a.balance=200;
}
}
class Account{
static int rate;
public int balance=100;
thanks
 
El Roy Cabildo
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes of course you cannot directy get the value "balance" without creating the object first(Account) because its a member variable. But with "rate" you can call it with or without creating the object because it is static variable...chaging it like personal.rate = 7 and business.rate =5. The variable "rate" is shared by both business and personal.
 
Jasper Vader
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for replying, but what i am asking is not about whether a new object has to be created to be sent to the deduct() method.
i am asking is it possible for deduct() method to be passed an Account object, and do things with the balance variable just by referencing the balance variable, and not a.balance? And then not have these changes visible outside the deduct() method?
a bit confusing, maybe i am going about asking these things a bit confusingly.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic