Search code examples
javaaccess-modifiers

Java - Protected method cannot be accessed from a subclass


  • I have the following Foo class which has the main method in it.
  • Foo has extended Nee.
  • Foo class is in com.package1 and Nee class is in com.package2.
  • The problem is I cannot access the protected method of Nee, from Foo class through its object. Why is that ?(where the theory says protected members can be accessed by subclasses or classes within the same package)

The Foo Class looks like below,

package com.package1;

import com.package2.Nee;

/**
  *
  * @author Dilukshan Mahendra
  */
public class Foo extends Nee{

    public static void main(String[] args) {
        Nee mynee = new Nee();
        /* mynee.sayProtected(); This gives me a compile error,
                                 sayProtected() has protected
                                 access in com.package2.Nee
        */
    }

}

The Nee Class is like below,

package com.package2;

/**
 *
 * @author Dilukshan Mahendra
 */
public class Nee {



    protected void sayProtected(){

        System.out.println("I'm a protected method in Nee!");

    }



}

Solution

  • As class com.package1.Foo and class com.package2.Nee are in two different packages so Nee class instance will not allow you invoke protected method of that class.

    Create the instance Foo which is subclass of Nee then invoke the protected method,.

    Foo foo = new Foo();
    foo.sayProtected()