Wednesday 15 February 2012

java - In which situations we make variables as public and methods as private? -


Currently I'm learning the basics of Java and C ++ I wrote the book us C ++ In almost every case, we have made the example variable public and for public purposes for security purposes. But this book also mentions that in some cases we make the variable public and do it in private ways ..

I am constantly thinking, in what case we will do this. Anyone can please explain it.

Private methods (or private member tasks in C ++ terminology) are mostly useful helpful tasks. For, think about this matter that you want to apply imperfections, but to ensure that your degree is always normal. You can then use a personal member function normal () which makes your fraction normal, and which is called after every operation, resulting in a non-normalized fraction, For example (C ++ code):

  square degrees {public: fraction (int num, int den = 1); Fraction operator + = (fraction transmission and other); Fraction operator * = (fractional storage and other); // ... private: int fraction, bottom; }; Fraction: fraction (integer number, int den): fraction (digit), divisor (den) {general value (;); } Fraction part :: operator = = (fraction transmission and other) {int new_den = denominator * other.denominator; Fraction = fraction * other.nameominator + bottom line * other Numerical; Incorporation = new_den; } Fraction part :: operator * = (fractional storage and other) {partial * = other Numerical; Divisor * = other.nameominator; Normal (); } Zero degrees: normal () {int factor = GCD (fraction, spore); Fraction / = factor; Divisor / = factor; }   

The specific use of one and the C ++ private works is based on the fact that private accessibility in C ++ is about control, not about visibility. When making virtual function virtual, it is able to check the unverified pre-post-status in the base class:

  class base {public: foo frobnicate (some arguments); Private: virtual foo do_frobnicate (some arguments) = 0; }; Foo Base :: Fraubenicate (some arguments) {check_ precondition (logic); Foo result = dot_frebnet (logic); Check_post_condition (foo); Return fu; } Classes generated from   

base will override the class do_frobnicate , while users will call frobnicate Always checks pre / postcondition no matter what the derived class does.

No comments:

Post a Comment