-1

Why this code runs fine??

package certification;
public class Parent {
    protected int x = 9; // protected access
    protected void z(){System.out.println(5);}
}


package other;
import certification.Parent;
class C extends Parent{}
public class Child extends C {
    public void testIt() {
        System.out.println("x is " + x);
        this.z();
    }

}

import other.Child;
class Test extends Child{
    public static void main(String args[]){
        new Child().testIt();
    }
}

This gives output:

x is 9

5

But how can subclass(Child) of subclass(C) can access protected member of class Parent.

PuNiT
  • 15
  • 4
  • 3
    Possible duplicate of [What does the protected modifier mean?](http://stackoverflow.com/questions/8637781/what-does-the-protected-modifier-mean) – khelwood Jan 19 '17 at 17:06
  • Another link that might help you understand the difference between access modifiers in java. http://stackoverflow.com/questions/215497/in-java-difference-between-default-public-protected-and-private – dnapierata Jan 19 '17 at 17:07
  • Possible duplicate of [In Java, difference between default, public, protected, and private](http://stackoverflow.com/questions/215497/in-java-difference-between-default-public-protected-and-private) – dnapierata Jan 19 '17 at 17:09

1 Answers1

0

In your example class Child extends C and class C extends Parent. This means Child is a subclass of Parent. Protected fields are visible both to all subclasses and to classes in the same package. https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Luk
  • 2,186
  • 2
  • 11
  • 32