javainheritanceaccess-protection

How does a java child class inherit access-protected parent fields?


This is a beginner question, but I've googled around and can't seem to find an answer.

Say I have a class person:

class Person {
  private String SSN;
  //blah blah blah...
}

and then I create a subclass OldMan:

class OldMan inherits Person {
  //codey stuff here...
  public void setSSN(String newSSN) {
    SSN = newSSN;
  }
}

It looks like I can't actually change the private fields from Person. I was under the impression that when OldMan inherited Person, it would have its own copies of the private variables that belonged to it. It seems like what's actually happening is that when I create an OldMan object, it creates the SSN field but... it somehow belongs to a Person object??

I realize I can just make SSN protected, but is that a best practice? What's actually going on here, and how can create a parent class that will have important fields access protected, without protecting them from child classes?


Solution

  • You can do something like,

    class Person {
          private String SSN;
          //blah blah blah...
    
        public String getSSN() {
            return SSN;
        }
    
        public void setSSN(String sSN) {
            SSN = sSN;
        }
    
    
        }
    
    public class OldMan  extends Person {
        //codey stuff here...
          public void setSSN(String newSSN) {
            super.setSSN(newSSN);
          }
    }