1

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?

Joseph Morgan
  • 210
  • 2
  • 8

2 Answers2

2

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);
      }
}
Vishal Gajera
  • 4,137
  • 5
  • 28
  • 55
0

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??

Yes. Exactly.

I realize I can just make SSN protected, but is that a best practice?

Exactly. That is how protected works, and you can safely use it.

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?

As you just said, make them protect, now they can access only by child's and with in the package.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307