Pregunta

  • 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!");

    }



}
¿Fue útil?

Solución

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()

Otros consejos

If you are clear that protected member can't accessed outside package without subclass then It doesn't matter where are you creating Nee class object to access its protected method either in its subclass or any where else. Its same thing. Only subclass know about protected member and can be accessed via subclass object.

members can be accessed by subclasses or classes within the same package. You are using two different packages.

Protected allows access to the member of the subclass. Here, you're trying to access the protected member of Nee when protected only allows access of the protected member on Foo.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top