0
votes

In Java, how can I access protected members in a different package?

package p1
    class base      
        protected int x

package p2
    import p1.*
    class derived extends base
        int x

class subderived extends derived
     int x

From subderived main I want to access x of p1.base as protected specification we can use only inheritance we can't use reference to access base x. To access derived x we can use super.x, but from subderived, how can we access base.x?

1

1 Answers

2
votes

Protected members are accessible from immediately derived and sub-derived classes without any qualifiers: rather than writing

base.x = 123;

you can write

x = 123;

and it will compile fine, as long as it is in a method of a derived class. However, in order for this to work, you need to remove members with the same name from the derived class itself: otherwise, the base member is hidden, and cannot be accessed through more than one level of inheritance hierarchy through the normal syntax of the language, i.e. without using reflection.