+ 1

public and private members of a class

Why can be private member of the class useful, if i cannot access it from outside? what can i do with it?

11th Oct 2016, 10:35 PM
Benedek Máté Tóth
Benedek Máté Tóth - avatar
2 odpowiedzi
+ 5
Say you have a class which counts numbers. class Counter{ private int counter; public Counter(){ counter = 0; } public void count(){ counter++; } public int getCounter(){ return counter; } } You'd use it like this: var c = new Counter(); c.count(); c.count(); Console.WriteLine(c.getCounter()); // will print 2 Now imagine if that private `counter` variable were public! You could just set it to whatever you want and all your counting would be messed up and wrong. And in a way it's your fault, you allowed the `counter` variable to be messed with. The way to deal with it is to make it private - that's like saying "you don't need to know about `counter`, just use the `count` and `getCounter` methods" to the person who will be using your class. Generally, try to make as many things private as possible - the less "surface area" your class has, the less a person using your class can screw up. If your class only has a few public members, you exactly know how your class will be used and what can and can't happen!
11th Oct 2016, 10:56 PM
Schindlabua
Schindlabua - avatar
+ 2
thank you, really clear and helpful answer:)
12th Oct 2016, 4:16 PM
Benedek Máté Tóth
Benedek Máté Tóth - avatar