What are public, private and protected in object oriented programming?
There are three access modifiers: public - the property or method can be accessed from everywhere. This is default. protected - the property or method can be accessed within the class and by classes derived from that class. private - the property or method can ONLY be accessed within the class.
Variables and methods defined with the private keyword may be accessed only by other methods within the class and cannot be accessed by derived classes. The private keyword is used in most object-oriented programming (OOP) languages, including C++, C# and Java.
In C++, there are three access specifiers: public - members are accessible from outside the class. private - members cannot be accessed (or viewed) from outside the class. protected - members cannot be accessed from outside the class, however, they can be accessed in inherited classes.
Protected, in C#, is a keyword used to declare the accessibility of a class member such that access to that member is limited to the containing class in which it is declared or to any class derived from the containing class.
They are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.
private
- Only the current class will have access to the field or method.
protected
- Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.
public
- Any class can refer to the field or call the method.
This assumes these keywords are used as part of a field or method declaration within a class definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With