Sunday, September 26, 2010

Access Modifiers

Ever wondered what those public, protected, and private keywords stand for? Well, they exist to take advantage of encapsulation (discussed in my previous post) in Java. Access modifiers provide a way to hide methods, attributes, or classes from being accessed from another class or package. There are 4 access modifiers, namely:
  1. public
  2. protected
  3. private
  4. default
The public modifier is the least restrictive among the four. Methods, attributes, constructors, or classes that are declared public can be accessed anywhere in any class and in any package (provided of course that they are imported).

The protected modifier is used on method, attributes, and constructors in a class. Classes, interfaces, and interface's methods and attributes cannot have a protected access modifier. Methods, attributes, and constructors that are protected can only be accessed within its classes' subclass, either within the same package or another. Any class within the same package can also access these methods, attributes, and constructors.

The private modifier is the most restrictive of all. Methods, attributes, constructors, as well as inner classes that are private can only be accessed within the enclosing class. However, interfaces and its methods and attributes cannot use the private access modifier.

Methods,attributes, constructor, and classes without public, protected, or private belong to the default access modifier. This modifier restricts access to any class, method, attribute, or class to only within the same package. Interfaces and its methods and attributes cannot use the default access modifier.

This example only shows how it is used in code:
package com.blogspot.codingineverydaylife.access.package1;
public class PublicClass1 {

    String defaulAttribute = "I am a default attribute.";
    public String publicAttribute = "I am a public attribute.";
    protected String protectedAttribute = "I am a protected attribute.";
    private String privateAttribute = "I am a private attribute.";

    public PublicClass1() {
        System.out.println("I am a public constructor");
    }

    void defaultMethod(){
        System.out.println("I am a default method");
    }
    
    public void publicMethod(){
        System.out.println("I am a public method");
    }
    
    protected void protectedMethod() {
        System.out.println("I am a protected method");
    }
    
    private void privateMethod() {
        System.out.println("I am a private method");
    }
}

No comments: