BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

What is protected Keyword in Java

By Chaitanya Singh | Filed Under: java

The protected keyword is an access modifier in java. It is used for variables, methods and constructors. The fields marked with protected keyword are only accessible inside same package or through inheritance.

Usage of protected Keyword

  • A protected variable or method can only be accessed inside the same package. However they can also be accessed outside package through inheritance. A subclass of this class can access the protected variables and methods of the parent class.
  • A class or an interface cannot be declared protected. This access specifier does not work for them.
  • As per the rules of method overriding, overriding method in sub class cannot be more restrictive so a subclass that is overriding protected method, must use either public or protected access modifier for overriding method.

Java protected variable Example

Here, we have two classes in two different packages. We are trying to access a protected variable of class, which is in different package. This will throw compilation error as protected access modifier doesn’t allow this.

//file 1: MyClass.java
package com.beginnersbook;
public class MyClass {
  protected String str="I am a protected variable of class MyClass";
}

//file 2: AnotherClass.java
package com.anotherpackage;
import com.beginnersbook.MyClass;

public class AnotherClass {
  public static void main(String[] args) {
    MyClass obj = new MyClass();
    System.out.println(obj.str);

  }
}

Output: Compilation error!

Let’s see if we place these classes in the same package then how the output changes:

class MyClass {
  protected String str="I am a protected variable of class MyClass";
}
public class AnotherClass {
  public static void main(String[] args) {
    MyClass obj = new MyClass();
    System.out.println(obj.str);

  }
}

Output: The program runs fine as the protected variable can be accessed inside same package.

I am a protected variable of class MyClass

Java protected method Example

The behaviour is similar to what we have seen with protected variables. It can be accessed inside the same package and cannot be accessed outside package except if it’s a subclass.

class MyClass {
  protected void demo(){
    System.out.println("Protected method demo in class MyClass");
  }
}
public class JavaExample {
  public static void main(String[] args) {
    MyClass obj = new MyClass();
    obj.demo();
  }
}

Output:

Protected method demo in class MyClass

Java protected class Example

There is no concept of protected class in Java so this program will throw a compilation error. Similarly, you cannot use protected keyword with interfaces.

protected class JavaExample {
  public static void main(String[] args) {
    JavaExample obj = new JavaExample();
  }
}

Output:

protected class example output

Java protected Constructor Example

A class can have protected constructor. You cannot create an object of class with protected constructor outside the package.

In the following example, we have two classes. A class JavaExample creates an object of class MyClass using protected constructor, program runs fine as they are in same package.

//File 1: MyClass.java
class MyClass
{
  //protected constructor
  protected MyClass(){
    System.out.println("protected constructor of MyClass");
  }
}
//File 2: JavExample.java
class JavaExample {
  public static void main(String[] args) {
    MyClass obj = new MyClass();
  }
}

Output:

protected constructor of MyClass

Overriding a protected method in subclass

A protected method can be overriden in the sub class, just remember the following rule:

  • An overriding method of subclass can only have public or protected access modifier else you will get a compilation error "cannot reduce the visibility of the inherited method".
  • This is because method in subclass cannot be more restrictive. The default and private access modifiers are more restrictive than protected so these cannot be used here.
//File 1: MyClass.java
class MyClass
{
  //protected method in parent class
  protected void demo()
  {
    System.out.println("Protected method demo of MyClass");
  }
}
//File 2: JavExample.java
class JavaExample extends MyClass {
  //overriding the demo() method
  protected void demo()
  {
    System.out.println("Overriding method demo");
  }
  public static void main(String[] args) {
    JavaExample obj = new JavaExample();
    obj.demo();
  }
}

Output:

Overriding method demo

Recommended Posts

  • Java Access Modifiers Tutorial
  • Java Super Keyword Tutorial
  • Java Inheritance Tutorial
❮ Java Keywords

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap