Previous | Home | Next |
The protected modifier makes a class member more visible than private modifier but less accessible than public modifier. This modifier may be applied only to class members viz. variables, methods, and inner classes—but not to the class itself. A class member declared protected is visible to the following elements:
-
The classes in the same package that contains the class that owns the protected member.
-
The subclasses of the class that owns the protected member. These subclasses have access even if they are not in the same package as the parent class.
The usage of protected modifier can be shown as,
Example
Java Tutorialslass ModifierDemo { private int i=10; protected int j=5; } Java Tutorialslass PublicModifier extends ModifierDemo { public static void main(String[] args) { PublicModifier obj=new PublicModifier(); System.out.println("The value of i is :"+obj.i); // cause a compile error as i's defined private. System.out.println("The value of j is :"+obj.j); // print the value of j =5, as j is declared protected } }
In java we cannot specify any modifier for the variables inside a method, and also we cannot specify the protected modifier for a class. When we do not specify any access modifier for an element, it is implied that the access is default. It can be applied to a class, a variable, or a method.
A class or a class member declared default i.e. with no access modifier specified is accessible from anywhere in the same package in which the accessed class exists. Consider the following code fragment:
package example; Java Tutorialslass ShowExample { private int i=10; void Show() { System.out.println("The value of i is :"+i); } }
Above code contains a method of default modifier show returning void, and it is contained in a package called example.
package example2; Java Tutorialslass ReviewExample extends ShowExample { Show(); // will cause compiler error }
The Show() method called in class ReviewExample causes a compiler error, as Show() method is declared default in ShowExample which is in a totally different package and, it is obvious that a default method cannot be accessed from a different package other than in which it is defined.
Previous | Home | Next |