Dremendo Tag Line

Access Specifiers in Java Programming

OOPs in Java

In this lesson, we will understand what is Access Specifiers in Java and how to implement them in class object programming.

What is Access Specifiers in Java?

In Java, access specifiers are used to specify the access level of a class or its members (data and methods). There are four access specifiers in Java:

  • public: When we declare class members as public, they are accessible from outside the class.
  • private: When we declare class members as private, they are only accessible within the class and are not accessible from outside the class.
  • default: When we declare class members with no access specifier is considered as default, they are only accessible within the package and are not accessible from outside the package.
  • protected: When we declare class members as protected, they are only accessible by any class within the same package or by any subclasses of the parent class in which the class members are declared as protected, regardless of whether the subclass is in the same package or a different package.

Note: A package is a container that contains classes in java.

We already know from the previous lessons how to use private and public access specifiers in a Java program. Now, we will see how to use a default and protected access specifier in a Java program.

video-poster

Example

import java.util.Scanner;

class Student
{
    int roll;		// default access specifiers
    protected int eng;
    protected int math;
};

// Inherit the class Student into Result
class Result extends Student
{
    private int total;
    private float per;


    public void input()
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter Roll: ");
        roll=sc.nextInt();
        sc.nextLine();		// consume the new line character \n left by the previous input
        System.out.print("Enter English: ");
        eng=sc.nextInt();
        System.out.print("Enter Math: ");
        math=sc.nextInt();
    }

    // Creating an instance method to calculate and store total and percentage
    public void calculate()
    {
        total=eng+math;
        per=(total/200.0f)*100;
    }

    void show()
    {
        System.out.println("Roll: " + roll);
        System.out.println("English: " + eng);
        System.out.println("Math: " + math);
        System.out.println("Total Marks: " + total);
        System.out.println("Percentage: " + per);
    }
}

public class Example
{
    public static void main(String args[])
    {
        Result x=new Result();
        x.input();
        x.calculate();
        x.show();
    }
}

Output

Enter Roll: 1
Enter English: 74
Enter Math: 88
Roll: 1
English: 74
Math: 88
Total Marks: 162
Percentage: 81.0

In the above example, we can see that the default and protected data members of the Student class are accessible from the Result class after inheriting the Student class in it.