The blog of Jafar Aliyev

Archive

Creation date:

Protected details

Lets look at the following example of protected usage.

package package1;
public class A {
   protected int x = 17;
 }

package package2;
import package1.A;

 class B1 extends A{
   public void printX(){
     System.out.println(x);
   }
 }

 public class B2 {
   public static void main(String[] args) {
      B1 b1 = new B1();
      System.out.println(b1.x);
   }
 }

Field x is protected in class A. Despite of location of class B1 in other package it can access the instance variable of class A because of inheritance. Now B1 is a subclass of A, hence we can think about instance variable x as a protected field of B1 too. Look to class B2. It is in the same packege with B1 and could see the protected instance variables of B1. But not. B2 can't see inherited protected instance variables and/or methods of other class in the same package. This code will not compile.

Now look at another example of protected field usage.

package package1;

 public class A {
   protected int x = 17;
 }

package package2;

import package1.A;

 public class B extends A{

   public static void main(String[] args) {
     A a = new A();
     B b = new B();
     System.out.println(b.x);
     System.out.println(a.x);
   }
}

Class B extenda class A and can see its protected variable x. The code System.out.println(b.x); will print the variable x. Bu what about accessing the protected variable x through reference (a.x) It will not compile. Because of the following rule. Even subclass of the class can't acces its protected members throuth reference it it is in the ather packege.
Protected variables/methods can be accessed only through inheritance !

Author: Jafar N.Aliyev (Jsoft)

Read also

Use instanceof carefully
Usage of 'instanceof' method in some situations will give you a compilation error

Wrapper objects

Static and instance initilization blocks

Overloading

Java access and nonaccess modifiers
Look at this cheat sheet for Java access and nonaccess modifiers

Implicit typecasting

Interface methods are always public

Static methods can not be overriden
Here I explain, why static methods can not be overriden

Implicit typecasting

Java Tips

Variable hiding

Postfix operators

Tricky Polymorphism

Pattern Matching

Default values

String equality

© Copyright

All articles in this site are written by Jafar N.Aliyev. Reproducing of any article must be followed by the author name and link to the site of origin(this site). This site also keeps the same rules relative to the articles of other authors.