Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access Modifier in Java not working as expected

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 Child was defined within Certification itself 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 Child was to extend Certification but Certification is defined elsewhere e.g. package two;)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading