The protected keyword in Java programming language
- Home
- Access modifiers
- The protected keyword in Java programming language
- On
- By
- 0 Comment
- Categories: Access modifiers, Keyword in Java
The protected keyword in Java programming language
The protected keyword in Java programming language
In this tutorial, we will discuss about the protected keyword in java programming language
protected is a keyword in java programming language and an access modifier. This keyword can be used to define a method or a variable of a class.
When a variable or a method is declared as protected, it can be accessed from
- within the enclosing class
- other class in the same package as in enclosing class
- sub class , regardless of packages
Note – When a variable is marked as public, it can be used and accessed from enclosing class and outside classes
Variable(protected)
Syntax
Syntax of the protected keyword in Java variable
<access modifier> <Variable_type> <variable_name>;
Example
protected String stu_name; // this is a protected variable. It can be invoked from other classes in the same package as its enclosing class.
Note – when a method is marked as protected, it can be executed from another class in the same package as in enclosing class
The protected keyword in Java
Program
Protected variable in same package
package sch; public class school{ protected int marks; }
The following class in the same package named as package sch;
package sch; public class student{ void getMarks(){ school sc=new school(); sc.marks=56; //access protected variable in same package } }
The following class in the different package. but it inherits (extends) studentclass properties. Hence it can access the variable age directly.
package sch1; import sch.school public class student extends school{ void getmarks(){ school sc=new school(); sc.marks=56; //you can access the protected variable in the //different package of only from inherited class } }
Different package and no inheritance
following class is in different package you cannot access the variable marks directly
package sch1; import sch.school public class student_Two{ void getMarks(){ school sc=new school(); sc.marks=56; //you cannot access the protected variable in the //different package of only from inherited class } }
Methods-(protected)
Syntax
Syntax of the protected key word in Java methods
<access modifier> <Variable_type> <method_name>();
Example
protected void run() {
}// this is a protected method. It can be invoked from the same package enclosing classes.
There are other Java language keywords that are similar to this keyword
Suggested for you