Home>

Right now, I'm studying Java and there is something I don't understand.

The book says that protected can be accessed for the same package or subclass, but I want to know why the num field cannot be accessed in the main class that inherits the Parent class.

The problem i am having

I get an error that num is being accessed protected

Source code
package silver.ex18;
/ **
 *
 * @author 2170145
 * /
public class Parent {
    protected int num = 10;
}
package silver.main;
import silver.ex18.Parent;
/ **
 *
 * @author 2170145
 * /
public class main extends Parent {
    public static void main (String [] args) {
        Parent p = new Parent ();
// Error below
        System.out.println (p.num);
    }
}
  • Answer # 1

    protected is accessible for the same package or subclass

    That's right, but it seems that many people misunderstand.

    You can't access it with the code provided because the Parent class isn't in the same package.
    If you want to use a new Parent class, you have to be in the same package.
    The main class inherits from the Parent class, but you don't look at the inherited num and you're doing a new Parent.

    If you want to access it, it will be as follows.

    public class main extends Parent {
        public static void main (String [] args) {
            main m = new main ();
            System.out.println (m.num);
        }
    }

    This is a digression, but Java recommends that class names start with a capital letter, so
    It is better to make it the Main class instead of the main class.