I am a newbie programmer who is working on a Java certification. So, when I was learning about access modifiers, I came across public, protected and private. To see if I learnt correctly, I wrote the following code:
package one;
public class Certification {
public static void main(String[] args) {
Child st= new Child();
st.methodTwo();
}
}
class Child
{
protected static void methodTwo()
{
System.out.println("This is methodTwo");
}
}
This is showing an output of "This is methodTwo". However, according to my textbook, a protected method is one that needs to be inherited by the sub-class in order to be accessed. In this case, Certification is not inheriting Child. So, how is it working without throwing an error ?
As per my textbook, for the code to work, it has to be like this:
public class Certification extends Child { //Inheritance
public static void main(String[] args) {
methodTwo();
}
}
class Child
{
protected static void methodTwo()
{
System.out.println("This is methodTwo");
}
}
Although not relevant to the question, if I replace protected with private in methodTwo(), it is throwing an error (as expected).
Why is this happening ?
Textbook Name: OCA JAVA SE 8. PROGRAMMER ONE GUIDE
>Solution :
In Java method or a variable marked as protected can be accessed:
- from the enclosing class (if
Childwas defined withinCertificationitself for example) - from other classes within the same package (what we are seeing here, both are defined within
package one;) - from sub classes, regardless of the packages (if
Childwas to extendCertificationbutCertificationis defined elsewhere e.g.package two;)