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
Note – When a variable is marked as public, it can be used and accessed from enclosing class and outside classes
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
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 } }
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
C# inverted full pyramid star pattern In this article, we will discuss the concept of…
C# Full Pyramid star pattern program In this article, we will discuss the concept of…
Program to count vowels, consonants, words, characters and space in Java In this article, we…
How to print multiplication table using Array in C++ language In this post, we will…
C Program to multiplication table using Array In this tutorial , we will discuss about…
Java program to check odd or even using recursion In this tutorial, we discuss a…