Protected members in a superclass inaccessible by indirect subclass in Java

12,022

Perhaps you're a little confused.

Here's my quick demo and shows an indirect subclass accessing a protected attribute:

// A.java
package a;
public class A {
    protected int a;
}

// B.java 
package b;   //<-- intermediate subclass
import a.A;
public class B extends A {
}

// C.java
package c; //<-- different package 
import b.B;
public class C extends B  { // <-- C is an indirect sub class of A 
    void testIt(){
        a++;
        System.out.println( this.a );//<-- Inherited from class A
    }
    public static void main( String [] args ) {
        C c = new C();
        c.testIt();
    }
}

it prints 1

As you see, the attribute a is accessible from subclass C.

If you show us the code you're trying we can figure out where your confusion is.

Share:
12,022
MSumulong
Author by

MSumulong

#SOreadytohelp

Updated on June 04, 2022

Comments

  • MSumulong
    MSumulong about 2 years

    Why is it that in Java, a superclass' protected members are inaccessible by an indirect subclass in a different package? I know that a direct subclass in a different package can access the superclass' protected members. I thought any subclass can access its inherited protected members.

    EDIT

    Sorry novice mistake, subclasses can access an indirect superclasses' protected members.

    • Jon Skeet
      Jon Skeet about 14 years
      It would be easier to see what you mean if you could give a concrete example.
    • Oskar Kjellin
      Oskar Kjellin about 14 years
      He means that in assembly a1 there is a class a. This class has a protected member. However, he cannot access the protected member from class b that extends a in assembly a2, I think.
    • danben
      danben about 14 years
      No, he means that he cannot access the protected member from class c in a2 that extends class b that extends class a.
    • Jay
      Jay about 14 years
      What do you mean by an "indirect subclass"? Do you mean a child of a child? Or what?
    • MSumulong
      MSumulong about 14 years
      Sorry I cannot post the code due to its sensitive nature. But Oscar was right it was an forgotten import declaration.
    • MSumulong
      MSumulong about 14 years
      @Jay, yes a child of a child.
    • OscarRyz
      OscarRyz about 14 years
      @MSumlong: I guess it right!!! :) I had the same error while creating the sample code in my answer, but since it was so small I figure out immediately. :)
  • OscarRyz
    OscarRyz about 14 years
    Let me guess, you should've forgotten a import declaration, as in: import b.B
  • Random
    Random about 14 years
    That would be quite difficult since most compilers will complain that the extened class doesn't exist.
  • Erick Robertson
    Erick Robertson over 11 years
    OP seems to have figured it out.