×

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in a superclass may only be accessed by subclasses in the other package or by any class inside the package of the protected members' class.

Class and interfaces are exempt from the protected access modifier. Although methods and fields can be declared protected, an interface's methods and fields cannot.

Protected access allows the subclass to access the helper variable or method while prohibiting attempts by unrelated classes to do so.

One of Java's access modifiers is referred to by the protected keyword. The protected methods or data members can be accessed from

  • like the same class.
  • similar packages' subclasses.
  • various classes inside the same packages.
  • various package subclasses.

Conditions for Accessing Protested keyword

  1. Not extending the parent class when calling a protected function reaching a restricted class.
  2. Utilizing a separate but similar package to access the display function.
  3. Utilizing the display feature of a different package.
  4. Using an override to access a protected class inside the same package.

Important Points to remember about protected keyword:

  • Inheritance must be used if one wants to access a protected modifier outside of a package.
  • When a function Object () {[native code]} is protected, users are prevented from creating a class instance outside of the package.
  • If a variable or method is protected during overriding, it can only be overridden by another subclass using the public or protected modifier.
  • Interfaces and outside classes are not protected.
  • The package includes access to the protected access modifier. It is also accessible outside of the package, but only via inheritance.
  • We are unable to give outside classes and interfaces protected status.
  • Creation of an instance of a class from outside the package is not possible if you make any constructors protected.
  • Any method that is being overridden must not be more restrictive than the original method, which must be stated in the subclass.
  • In accordance with the preceding statement, if you give any method or variable the protected access modifier, only the public or protected access modifiers may be used to override it in a subclass.

Examples of Protected Keyword

Example 1:

An illustration of how to check whether a protected variable is usable outside of the package.

//save by All.java  
package com.java.


public class All { 
 protected String msg="class protected is outside the class after accessing";
}  
//save by ProtectedExample1.java  
package com. Java lang;
import com.java. All;


public class ProtectedEx1 {  
public static void main (String [] s) {  
    All am=new All();
   System.out.println(am.msg);
}  
}  

Output:

Error: Unresolved problem

Example 2:

an illustration of how to check whether a protected variable is available outside of the class and within the package.

class All { 
 protected String msg="class protected is outside the class after accessing";
} 
public class ProEx2 {  
public static void main (String [] s) {  
    Allam=new All();
   System.out.println(am.msg);
}  
}  

Output:

class protected is outside the class after accessing

Example 3:

an illustration to implement whether the protected method is available outside of the package or not.

package com.java.
public class All {  
protected void mss ()  
 {  
     System.out.println("method of protected is accessedoutside the package class");
 } 
}  
//save by ProtectedEx3.java  
package com. Javalang ;
import com.java. All;


public class ProtectedEx3 {  
public static void main (String [] s) {  
    All am=new All ();
   am.mss ();


}  
}  

Output:

Error: Unresolved compilation problem

Example 4:

an illustration of how to use inheritance to determine whether a protected method is available outside of the package.

package com.java.
public class All {  
protected void mss ()  
 {  
     System.out.println("method of protected is accessed outside the package classby impilementing inheritance");
 }  
}  
//save by ProtectedEx4.java  
package com. Javalang;
import com.java. All;


public class ProtectedEx4 extends All {  
public static void main (String [] s) {  
    ProtectedEx4 am=new ProtectedEx4();
   am.mss ();
}  
}  

Output:

method of protected is accessed outside the package classby implementing inheritance

Example 5:

protected class ProtectedEx5 {  
void disp ()  
{  
    System.out.println("accessing the outer protected class");
}  
public static void main (String [] s) {  
    ProtectedEx5 paa=new ProtectedEx5();
paa. disp();
}  
}  

Output:

Error: Unresolved problem compilation

Related Topics

How to achieve Multiple Inheritance in Java

Multiple Inheritance is the type of inheritance where one class inherits the properties of more than one super class. For example, class Child inherits (extends) the classes Father and Mother....

4 minutes read.

Java Continue Keyword

The java keyword ‘continues’ has also been called as java continue statement.The main concepts of the java continue statement or keyword is used in the controlling of the loop structure.Java...

3 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

What is the ambiguity problem in Java?

The ambiguity problem in Java occurs when a method or constructor is overloaded with two or more methods with the same name but different parameters. This can confuse when multiple...

6 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

URLConnection Class

What is the URL? URL stands for Uniform Resource Locator, is used to specify addresses on the World Wide Web. A URL relates to the identification of any resource connected to the web. URL syntax: Protocol://hostname/other_information(files...

6 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.