Home > Java > javaTutorial > body text

Protected Keyword in Java

WBOY
Release: 2024-08-30 15:22:35
Original
234 people have browsed it

Protected keywords are keywords that are used to restrict the scope within which the variable, method, and constructors can be accessed. It is one of the types of access modifiers in Java. They are used to differentiate between the scope of methods, variables, constructors, and classes. There are 4 types of access modifiers in Java, and they are:

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests
  1. Default keyword: They can be accessed only within the package and cannot be called outside it. As the name suggests, it is automatically assigned as the default when no access specifier is mentioned.
  2. Public keyword: They can be accessed from anywhere in the program. This means it can be used from the same or different classes and the same or a different package.
  3. Private keyword: They restrict the keywords to a higher level by not allowing them to be accessed from anywhere outside the class itself.
  4. Protected keyword: In this article, we shall get to know more about protected keywords.

Once a variable or a method is marked as protected, it can only be accessed by the below methods:

  • Inside the same class in which it is declared.
  • From other classes which are also in the same package as the declared class.
  • Classes inherited from the declared one, irrespective of their package.

Protected keywords are like a combination of both public and private keywords since they were introduced to access the variables outside the class (which is not possible in the case of private keywords) and maintain that only certain methods can inherit the same.

Syntax

Protected keywords are declared with the keyword prefixed to them as “protected”. We first declare the protected keyword in one of the class called “MyClass” as below:

class MyClass {
protected String name = "Katy";
protected int token= 55;
}
public class SubClass extends MyClass {
public static void main(String[] args) {
SubClass obj = new SubClass();
System.out.println(obj.name + "'s token number is: " + obj.token);
}
}
Copy after login

Here the class “SubClass” extends “MyClass”, and hence the protected keyword can be used here by creating an object of SubClass and by calling the variables.

Output:

 Protected Keyword in Java

Protected keywords can only be used at the member level, i.e. inner classes declared outside of a function and non-static. Protected keyword is different from that of private as they can be accessed outside of a class and in the subclass of another package.

Some of the restrictions on using protected keywords are:

  • They cannot be used for declaring classes as protected.
  • Interfaces cannot be declared as protected.
  • Accessibility outside the package is only through inheritance.
  • A constructor that is made protected cannot be accessed outside the package by creating its instance.

Examples of Protected Keyword in Java

Let us go through some examples where we can understand the concept of protected keywords better.

1. Calling protected keyword without extending the parent class

Here we try to call the keyword from the parent class of “package1”. “ProtectedExample2” is created in “package2”, and the keyword “disp” is called here. But the code will not be able to access the keyword since the child class has not inherited its value from the main class and will throw an exception as shown.

Code:

package com.package1;
public class Example {
protected String disp="Printing message from protected variable from package1";
}
//Create new package as com.package2
//Create new class as ProtectedExample2
package com.package2;
import com.package1.Example;
public class ProtectedExample2 {
public static void main(String[] args) {
ProtectedExample2 a=new ProtectedExample2();
System.out.println(a.disp);
}
}
Copy after login

Output:

Protected Keyword in Java

2. Accessing a protected class

In this example, we try to access the class “ProtectedExample5”, which is protected. This causes a compilation error.

Code:

protected class ProtectedExample5 {
void display()
{
System.out.println("Try to access outer protected class");
}
public static void main(String[] args) {
ProtectedExample5 p=new ProtectedExample5();
p.display();
}
}
Copy after login

Output:

Protected Keyword in Java

3. Displaying protected keyword from the same package but different class

In the below example, we first create a package called “com.package1” and create a new class by the name “Example”. Here we declare our keyword “disp” is protected. We shall try to display this protected keyword using the class “Example1”. For this, first, an object of parent class “Example1” needs to be created and then print the value assigned to the keyword “disp”.

Code:

package com.package1;
public class Example {
protected String disp="Printing message from protected variable from package1";
}
class Example1 {
public static void main(String[] args) {
Example obj=new Example();
System.out.println(obj.disp);
}
}
Copy after login

Output:

Protected Keyword in Java

4. Displaying protected keyword from a different package

Using the same code as above, we shall see how to call the protected keyword by creating a different package, “package2”. A protected keyword can be accessed only through inheritance from package1; hence “ProtectedExample2” is extended from “Example”. In a similar way as the first example, we have to create an object of the class “ProtectedExample2” in order to access the protected keyword from package “com.package1”.

Code:

package com.package2;
import com.package1.Example;
public class ProtectedExample2 extends Example{
public static void main(String[] args) {
ProtectedExample2 a=new ProtectedExample2();
System.out.println(a.disp);
}
}
Copy after login

Output:

Protected Keyword in Java

5. Accessing a protected class by overriding to sub-class

Here the class is declared as protected inside the inherited class “Example5”. Also, a protected class called “Example” is declared outside the function but in the same package. When an object of “Example5” is created and the protected class “disp()” is called, we can observe that the overridden method is called instead of the outside class. This is because we shall not be able to import “com.package1” and its class “Example” since it is not visible and causes a compilation error.

Code:

//Create a file by Example.java
package com.package1;
class Example
{
protected void disp()
{
System.out.println("Printing from protected class in the outside function");
}
}
//Create a class by the name Example5.java
public class Example5 extends Example {
protected void disp()
{
System.out.println("Accessing the overriden function");
}
public static void main(String[] args) {
Example5 exp=new Example5();
exp.disp();
}
}
Copy after login

Output:

Protected Keyword in Java

Importance of Protected Keyword

The importance of protected keyword in java is:

  • These keywords allow the classes or their variables to be inherited from their parent class which is not possible with any other restricted keyword such as private.
  • A protected keyword is the combination of a private keyword’s advantage and that of a public keyword. It eliminates the disadvantage of public keyword that the variable or class be accessible from anywhere in the program by restricting the scope.

Conclusion

As shown in the above examples, we choose protected keywords depending on the access level we require at the code level. They help greatly in cases where the same variable or class needs to be accessed from other inherited methods in the program. A parent-child relationship is always present between the parent class and its sub-classes which are using the protected keyword.

The above is the detailed content of Protected Keyword in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!