The protected keyword serves as an access modifier. It can be used with variables, methods, constructors, and inner classes. This modifier provides a level of access control that allows access within the same package and by subclasses, even if they are in different packages.
It restricts the visibility of a class and its members. If a class member is marked as protected, it can be accessed by the members of its own class, its subclasses, and classes in the same package. However, it cannot be accessed by any class outside the package.
The methods or data members declared as protected can be accessed from:
Syntax for a protected Variable
Syntax for a protected Method
Syntax for a protected Class
Output:
The score is: 200
Output:
Score of TestMatch is 400.
Output:
Method of protected class invoked.
Output:
Parent Class Protected Constructor
The protected keyword in the context of a package allows subclass access but restricts access from non-subclass classes.
Output:
Protected method from the Parent class
Let's see some other scenarios of using protected keyword.
In the following program, we have created two packages, mypackage1 and mypackage2. In class A, we have declared and defined a protected method show(). Class A is public because we will access it in mypackage2.
Here, note that the method show() will not be accessed because the child class has not inherited its value from the main class. Hence, a RunTimeException will occur.
When we run the above code, we get the RunTimeException.
In the following program, we have declared class A as protected and extended this class in mypackage2. When we try to invoke the show() method of class A from the Main class, it shows a Runtime Exception.
When we run the above code, we get the RunTimeException.
Output:
tpointtech
Output:
tpointtech
Output:
Child Class
We request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India