on Leave a Comment

Java Access Modifiers

We can set the accessibility of any method or data members using access modifiers.

Java has four access modifiers

- Default
- Private
- Protected
- Public

Default

If you do not specify any other access modifier, then it is default access modifier by default.

If data or method members of a class declared as default access modifier, they are accessible only from the class of same package. 

Example:

package p1;
class A
{
 void display()
 {
  System.out.println("Iam in class A");
 }
}

package p2;
import p1.*;

class B
{
 public static void main(String[] args) {
  A obj1 = new A();
  obj1.display();
 }
}

Output:

Compile time error

This show compile time error because default members cannot be accessed from outside the package.

Private

private is a keyword in java programming language

The data or method members declared as private can be only accessible in the class in which they are declared.

Class and interface cannot be private but class inside a class can be private.

Private members cannot be accessible by the other classes of the same package.   

Other class can indirectly access private variables through public methods. 

If we make private constructor of a class, then we can not make object of that class from outside the class 

Example:

class A
{
 private int age;
 public void setage(int x)
 {
  age = x;
 }
}
class PrivateMembers
{
 public static void main(String [] args)
 {
  A obj = new A();
  obj.age = 18;    // Compile time error
  obj.setage(18);  // This will work 
 }
}

Protected

protected is a keyword in java programming language.

The data or method members declared as protected can be accessible within same package or outside the package through inheritance.

Class and interface cannot be protected, but class inside a class can be protected.

Example:

package p1;

public class A
{
 protected void display()
 {
  System.out.println("Iam in class A");
 }
}

package p2;
import p1.*;

class B extends A
{
 public static void main(String[] args) {
  A obj1 = new A();
  obj1.display();
 }
}

Output:


Iam in class A


Public 

public is keyword in java programming language.

The data or method members declared as public can be accessible anywhere in a program.

Public access modifier has the widest scope among all other modifiers.

Example:

package p1;

public class A
{
 public void display()
 {
  System.out.println("Iam in class A");
 }
}

package p2;
import p1.*;

class B 
{
 public static void main(String[] args) {
  A obj1 = new A();
  obj1.display();
 }
}

Output:


Iam in class A



0 comments:

Post a Comment