Java - What type are protected variables in subclasses?

Viewed 45

Recently I was practicing inheritance topic in Java. I came across this statement that "protected member variables in super class are private in a subclass".

My question is, if a sub class itself is a parent of another subclass, will that subclass be able to access the member variables of the base class?

public class A
{
    protected int a;

    public A(int a)
    {
        this.a = a;
    }
}

public class B extends A
{
    public B(int a) 
    {
         super(a);
    }
}

public class C extends B
{
    public C(int a)
    {
        super(a);
    }

    @Override
    public String toString()
    {
        return ("" + this.a);
    }
}

public class Test
{
    public static void main(String args[])
    {
        C c = new C(5);
        System.out.println(c);
    }
}

Would C, a sub-sub-class of A, be able to access a, since by the above logic, protected becomes private in B and private variables cannot be inherited?

Testing this does print 5, how does this work then?

1 Answers

I came across this fact that "protected member variables in super class is private in subclass".

Let me correct that for you:

I came across this lie that "protected member variables in super class is private in subclass".

As your experiment shows, your 'fact' was gobbledygook. Not sure where you got it from; terms are nebulous and perhaps the sentence you read was associating different meanings to these words (private, protected, member variable, subclass, superclass), but as these words are fairly well defined I'm having a hard time imagining what it might be driving at. Perhaps a style directive (as in, you SHOULD treat protected things from the parent of your parent as if they were private, i.e. don't touch em).

If that's the style directive though, I disagree with it as well. The obvious argument is 'they are implementation details of your parent class' and this falls on its face in just about every reasonable usage of inheritance, so unless there is another reason I'm missing, that's not right either.

Related