• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

scope of objects

 
jignesh soni
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Game{
Player p1;// player is another public class in package
Player p2;
Rule r1;

public void playerDetails(){
p1 = new Player();
p2 = new Player();
Player p3 = new Player();
// other code
}

public void rulesOfGame(){
r1 = new Rule();
Rule r2 = new Rule();
p1 = new Player();

}
}

References p1, p2 and r1 are created as instance variables and object is created in playerDetails() and rulesOfGame(). So the scope these references will be only limited to the scope of these methods. If I need to use p1 reference in another method, then do I have to create Player object in that method or can I directly use p1 reference on any of Player methods once object is created in another method? If I have create new object in anpther method to use p1, then its like local variable with only difference of ame name used in other method rihght ?
player p3 reference zand Player it refers to are both created loaclly so its a local variable. So I guess, I cant use p3 reference outside the method in which it is declared.

Pls explain
 
Henry Wong
author
Marshal
Pie
Posts: 21024
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
References p1, p2 and r1 are created as instance variables and object is created in playerDetails() and rulesOfGame(). So the scope these references will be only limited to the scope of these methods.


No.... The scope of instance variables is available to any code that has access to the instance -- either directly with the "this" reference, or indirectly with an external reference. It doesn't matter when the object that is being referred to was assigned.

player p3 reference zand Player it refers to are both created loaclly so its a local variable. So I guess, I cant use p3 reference outside the method in which it is declared.


Yes, a local variable goes out of scope when the method terminates -- so in order to access the object referenced by p3, you would have needed to save it to some other reference that is still in scope.

Henry
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe you are sure about instance variables and local variables as the way you have told the things prove that you are aware!

It depends on the place where you declare the variables and NOT where you initialize them.

So, an instance variable is still an instance variable even if its getting initialized or reassigned in any of the instance methods!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic