Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Understanding Access Specifiers in Java

In this lesson, you will learn

  • Access Modifiers in Inheritance
  • Examples

 

Access Modifiers in Inheritance

Access modifiers determine whether inherited classes can access the superclass’s members (fields, methods, and constructors).

The four access modifiers in Java are:

 

 

Here is the summary table of access modifiers in Java

 

Example 1: Using Access Modifiers

Step-1: Create a Package name ‘pack1’ and create 2 classes in that.

 

package ch10.l2.pack1;

//Class A is in the 'pack1' package
public class A {
	private int privateVar = 1; // Accessible only within class A
	int defaultVar = 2; // Default access, accessible within the package
	protected int protectedVar = 3; // Accessible within the package and 
	// by subclasses of A, even if they are in different packages
	public int publicVar = 4; // Accessible from any other class

	public void display() {
		System.out.println("Private: " + privateVar);
		System.out.println("Default: " + defaultVar);
		System.out.println("Protected: " + protectedVar);
		System.out.println("Public: " + publicVar);
	}
}

//Class B is in the 'pack1'package and is a subclass of A
class B extends A {
	public void displayVars() {
		// System.out.println("Private: " + privateVar); 
	    // Compile-time error: cannot access privateVar
		System.out.println("Default: " + defaultVar); // Accessible
		System.out.println("Protected: " + protectedVar); // Accessible
		System.out.println("Public: " + publicVar); // Accessible
	}
}

 

Step-2: Create a Package name ‘pack2’ and create 2 classes in that.

package ch10.l2.pack2;

import pack1.A;

class C extends A {
	public void displayVars() {
		// System.out.println("Private: " + privateVar); 
	    // Compile-time error: cannot access privateVar
		// System.out.println("Default: " + defaultVar); // Not Accessible
		System.out.println("Protected: " + protectedVar); // Accessible
		System.out.println("Public: " + publicVar); // Accessible
	}
}
public class TestAccess {
    public static void main(String[] args) {
        A obj = new A();
        C objC=new C();
        // System.out.println(obj.privateVar); 
        // Compile-time error: privateVar has private access in A
        // System.out.println(obj.defaultVar); 
        // Compile-time error: defaultVar is not public in A; 
        // cannot be accessed from outside package
        // System.out.println(obj.protectedVar); 
        // Compile-time error: protectedVar has protected access in A
        System.out.println("Public Var: "+obj.publicVar); // Accessible
        objC.displayVars(); // Accessible
    }
}

Output

Public Var: 4
Protected: 3
Public: 4

 

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review