c# - Encapsulation : what Getter returns? -
in encapsulation readonly set write only
why output 11110 when not using special member function?
code:
class practice_4 { static void main(string[] args) { example abc = new example(); // abc.roll_ = 11; console.writeline(abc.roll_ ); console.readline(); } } class example { private int roll = 11110; public int roll_ { { return roll ; } //set{ // if (value > 10) // { roll = value; } // else // { console.writeline("error"); } //} } //public example() //{ // roll = 110; //} }
output :
11110
but when use special member function : public example()
class practice_4 { static void main(string[] args) { example abc = new example(); console.writeline(abc.roll_ ); console.readline(); } } class example { private int roll = 11110; public int roll_ { { return roll ; } } public example() { roll = 110; } }
so display output:
110
and discard 11110
to answer question "why output 11110 when not using special member function?"
the special member function in class constructor of class, means special function initializes/constructs object class definition, rule remember here is, constructors called after private variables statements , when constructor finished construction finished, means class's internal state(variables) assigned(among other things).
however if initialize private variables in private int roll = 11110;
line, line executes before constructor called. overwriting value of roll in constructor, value of private variable gets overwritten.
Comments
Post a Comment