OOP Mwaks

Topics: Java, Object-oriented programming, C++ Pages: 4 (6094 words) Published: December 4, 2014
Describe any two access modifiers as used in java programming language, write a sample java code to show how each can be used. Private Access Modifier - private:
Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself. Private access modifier is the most restrictive access level. Class and interfaces cannot be private. Variables that are declared private can be accessed outside the class if public getter methods are present in the class. Using the private modifier is the main way that an object encapsulates itself and hide data from the outside world. Example:

The following class uses private access control:
public class Logger {
private String format;
public String getFormat() {
return this.format;
public void setFormat(String format) {
this.format = format;
Public Access Modifier - public:
A class, method, constructor, interface etc declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe. Example:

The following function uses public access control:
public static void main(String[] arguments) {
// ...
The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class. Protected Access Modifier - protected:
Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class. The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected. Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it. Explain why java can...
Continue Reading

Please join StudyMode to read the full document

You May Also Find These Documents Helpful

  • Oops Essay
  • Oops Essay
  • Oops Essay
  • Java Oop Essay
  • Adv /Dis adV of OOP Essay
  • Oop Inheritance Essay
  • Introduction to OOP Essay
  • Oops (Bca) Essay

Become a StudyMode Member

Sign Up - It's Free