Java Made Simple: Java protected and protected method

Java protected specifier and protected method are explained also with method overriding rules. Given Example with Screenshot in Simple terms for a Beginner. Go on read.

"public" specifier does not give any restrictions to any class from any package. But "protected" gives a small restriction over public.

Restrictions of protected specifier

  1. If a member of a class is protected, it can be called by the classes of the same package without any restrictions as if public.
  2. Other package classes can access only if they extend or inherit the class. That is, subclasses other packages only can access.

Note: Variables and methods of a class are known as members of a class. Constructors are not members of a class. Why? A member can be called with an object where as constructor cannot be. You should use access with constructor but not call. That is, You can access a constructor but you cannot call a constructor. You can access a constructor by creating an object only.

In the following program Test class contains a protected display() method and public show() method. The subclass Demo can use both.

Following example on protected method gives clarity over overriding rules.
class Test
  protected void display()
    System.out.println("Hello 1");
  public void show()
    System.out.println("Hello 2");
public class Demo extends Test
  public static void main(String args[])
    Demo d1 = new Demo();
    d1.display();	// works fine;	        // works fine

In the above code, both Test and Demo happened to be in the same package (default package). The program works fine even Demo belongs to other package also (try once).

================Would you like to dig more into?=================

1. Java Private variable accessibility (Private access specifier)
2. What is Java private and private variable?
3. Can you override private method?
4. Access Specifiers & Access Modifiers

Leave a Comment

Your email address will not be published.