0

enter image description here

For the above hierarchy, Below is the code from pkg1,

package ProtectedAccess.pkg1;

public class T {

    protected int f;
    protected void m(){

    }

}

Below is the code from pkg2, where test2 is tested by replacing X with class T or A or B or C or S or D or E or F or G or H.

package ProtectedAccess.pkg2;
import ProtectedAccess.pkg1.*;

class A extends T {}
class B extends T{}
class C extends B{}

public class S extends B{
    void test1(){
        f = 42;
        m();
    }

    void test2(X  t){
        t.f = 42;
        t.m();
    }

}

class D extends S{}
class G extends D{}
class E extends S{}
class H extends E{}
class F extends S{}

--

1) If X is replaced with T or A or B or C, then compiler error.

2) If X is replaced with S or D or E or F or G or H, then things code works fine.

How do I understand the working of two scenarios from aforementioned points? Please help!!!

overexchange
  • 15,768
  • 30
  • 152
  • 347
  • it also does work for `class M extends S{}`. – wero Jul 30 '15 at 19:08
  • @SotiriosDelimanolis Did you go thru the question? – overexchange Jul 30 '15 at 19:30
  • 1
    I did and Jon Skeet answers it very well in the linked duplicate. Read the bold part (from the JLS) of their answer very carefully. – Sotirios Delimanolis Jul 30 '15 at 19:38
  • @SotiriosDelimanolis Do you mean, If you place `X` with `B` then one can send `new B()` object, then this is not access of protected members thru inhertiance? Is that what you are saying? – overexchange Aug 06 '15 at 09:08
  • 1
    Look at the accepted answer's bolded quote. _if and only if the type of `E` is `S` or a subclass of `S`_ In your field access, `t.f`, `t` would be of type `B` which is not `S` nor a subtype of `S`. It is therefore not allowed. This is all decided at compile time. The argument you pass to the method invocation is meaningless. – Sotirios Delimanolis Aug 06 '15 at 14:36

0 Answers0