Page 1 of 1

About Question enthuware.ocajp.i.v7.2.1330 :

Posted: Mon Mar 17, 2014 11:22 pm
by fasty23
Explanation said:
"protected
It will allow the subclasses and the classes in same package to access the
method."
I think this definition is for "default" not protected.
Is it right?

Re: About Question enthuware.ocajp.i.v7.2.1330 :

Posted: Mon Mar 17, 2014 11:39 pm
by admin
No, it is correct. subclasses can be in any package while classes in the same package do not need to be subclasses.

Re: About Question enthuware.ocajp.i.v7.2.1330 :

Posted: Wed Nov 26, 2025 12:12 pm
by thaednevol
Hello!

I have this example:

package p1;

public class Base {
protected void show() {
System.out.println("Base show()");
}
}

And

package p2;

import p1.Base;

public class Child extends Base {
public void test() {
show(); //1

Base b = new Base();
b.show(); //2
}
}

The question states 'enable all the subclasses to access a method defined in the base class', but Child is a subclass of Base, but it cannot access the method defined in Base class, and it is defined as protected

Re: About Question enthuware.ocajp.i.v7.2.1330 :

Posted: Thu Nov 27, 2025 8:51 am
by admin
There is an important nuance associated with protected access. It does enable the child class to inherit (and thus accessible) the method defined in the superclass but that doesn't mean it can call that method on a base class reference. The subclass can call this method only on the child class reference. Technically, it can be called only on the type of the object in whose implementation this child class participates in. You can read more about it here: https://docs.oracle.com/javase/specs/jl ... #jls-6.6.2

Re: About Question enthuware.ocajp.i.v7.2.1330 :

Posted: Thu Nov 27, 2025 8:51 am
by admin