java - Access to non-static variable from static context -
this question has answer here:
i trying access boolean variable stay
class montyhall
cannot because non-static , trying access in static context here code:
public void updatestatistics(door door1, door door2, door door3) { this.numgames = this.numgames + 1; onedoor(door1, 0); onedoor(door2, 1); onedoor(door3, 2); if (montyhall.stay == true){ this.numstay = this.numstay + 1; } else{ this.numswitch = this.numswitch + 1; } }
the variable stay located in class montyhall
. appreciated confused how fix properties of class montyhall
:
public class montyhall { boolean stay; door = new door("a"); door b = new door("b"); door c = new door("c"); public montyhall(door a, door b, door c){ this.a = a; this.b = b; this.c = c; }}
am trying access boolean variable stay class montyhall cannot because non-static , trying access in static context
everything clear now. variable stay
instance variable belongs each individual object of class montyhall
. shouldn't contemplate making static
resolve error.
to access instance variable, need create object first. (since belongs particular object , not class):
montyhall hall = new montyhall(); hall.stay; //access stay object of montyhall
in rule of data protection , encapsulation, may consider making stay
variable private , use getters
, setters
access it.
so if set stay
private, access this:
hall.getstay();
last not least, java not have global variables. rather common misconception perceive class variables (static variables) global.
Comments
Post a Comment