OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 4 : Access Control for Class Members in Java

 

Unit - 2

Topic 4 : Access Control for Class Members in Java

In Java, encapsulation not only links data with the code that manipulates it, but it also controls how the data and methods are accessed from outside the class. This is achieved using access specifiers (also called access modifiers).

Java provides four levels of access control:

  1. public

  2. private

  3. protected

  4. default (no specifier)


1. public

  • A public member is accessible from anywhere in the program.

  • It can be accessed by classes in the same package as well as classes in different packages.

Example:

class Demo { public int x = 10; // public member } public class TestPublic { public static void main(String[] args) { Demo obj = new Demo(); System.out.println(obj.x); // Accessible anywhere } }

2. private

  • A private member can be accessed only within its own class.

  • It is not visible to other classes, even if they are in the same package.

  • This is the most restrictive access level.

Example:

class Demo { private int x = 10; // private member void display() { System.out.println("x = " + x); // Accessible here } } public class TestPrivate { public static void main(String[] args) { Demo obj = new Demo(); // System.out.println(obj.x); // ❌ Error: x has private access obj.display(); // ✅ Access through a public method } }

3. protected

  • A protected member can be accessed:

    • Within the same class.

    • Within the same package.

    • By subclasses (even if they are in different packages).

Example:

class Demo { protected int x = 10; // protected member } class SubDemo extends Demo { void show() { System.out.println("x = " + x); // Accessible in subclass } } public class TestProtected { public static void main(String[] args) { SubDemo obj = new SubDemo(); obj.show(); // Accessible through subclass method } }

4. Default (Package-Private)

  • If no access specifier is used, the member is accessible only within the same package.

  • This is called package-private access.

Example:

class Demo { int x = 10; // default access } public class TestDefault { public static void main(String[] args) { Demo obj = new Demo(); System.out.println(obj.x); // Accessible because same package } }

Access Control Table

ModifierSame ClassSame PackageSubclass (diff package)Other Packages
public
protected
default
private

Key Notes

  • private → Most restrictive, best for encapsulation.

  • public → Least restrictive, used for APIs and widely accessible methods.

  • protected → Useful in inheritance.

  • default → Good for package-level encapsulation.

Comments

Popular posts from this blog

Career Guide - B.Tech Students

Artificial Intelligence - UNIT - 1 Topic - 1 : Introduction to AI (Artificial Intelligence)

Financial Aid for Students: Scholarships from Government, NGOs & Companies