-4

I make a variable that has been protected in the parent class but when I try to access it from subclass with the help of the parent class name I am unable to access it. As parent class and subclass are in different packages.

I tried the below code, can I know why I am unable to access it.

package basic;

public class AccessModifiers {

    protected int age;

    public AccessModifiers() {
        super();
    }

    public AccessModifiers(int age) {
        super();
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}


package inheritance;

import basic.AccessModifiers;

public class Inheritance extends AccessModifiers {

    public Inheritance(int age) {
        super(age);
    }

    public static void main(String[] args) {

        Inheritance inheritance = new Inheritance(23);
        System.out.println("Age:" + AccessModifiers.age);
    }
}
Mat
  • 202,337
  • 40
  • 393
  • 406
Aneesh
  • 1
  • 1

1 Answers1

2

This has nothing to do with the access modifier, but rather with the field not being static. Just replace

AccessModifiers.age

with

inheritance.age

Note that protected access allows you to access the field from the child class. Once you move the main method to another class that is not a subclass or in a different package, the field would no longer be accessible, and you would use the getAge() method instead.

M A
  • 71,713
  • 13
  • 134
  • 174