Understanding protected in Java

49 views Asked by At

Some years now that I'm developing in Java and using protected keyword. But I'm now facing a very simple case of protected usage that I don't understand...

Let's say I have a first package, packagea with the Parent class:

package packagea;

public class Parent {

    protected void doSomething(){
        System.out.println("I'm eating");
    }
}

And a second package, packageb, with a Child class:

package packageb;

import packagea.Parent;

public class Child extends Parent {

    public void execute(){
        Child child = new Child();
        child.doSomething();

        Parent parent = new Parent();
        parent.doSomething();   //Will cause java: doSomething() has protected access in packagea.Parent
    }

}

If I look at the protected modifier definition for Java, I see :

Allows access to any subclass or to other classes within the same package.

Why is parent.doSomething() not accessible since we are inside Child which is a subclass of Parent?

0

There are 0 answers