1

I have an abstract class called myClass, and that class has a private datafield called x. I have a public getX method, and an abstract setX method.

I have a subclass called mySubclass which extends myClass. I'm trying to create a concrete setX method, but the code:

public void setX() {
  x = 24.99;
}

gives me an error, as x is private. Am I supposed to set the x datafield to protected or public, or is there a way to keep x private?

Space Ostrich
  • 413
  • 3
  • 5
  • 13
  • 1
    Seeing that you actually are aware that the `protected` keyword exists, I suggest that you reflect over this question: *Why do you want the field to be private and not protected?* – RaminS May 30 '16 at 05:17
  • I've been told and understand why private is preferable whenever possible, I was unsure as to whether private was possible in this scenario. – Space Ostrich May 30 '16 at 05:23
  • If you _really_ want it private in the superclass then you must provide a non-abstract setter _in the superclass_, maybe itself protected and named, say, `_setX`. Then the subclass could use that setter. – Jim Garrison May 30 '16 at 05:27

3 Answers3

5

You cannot set private fields of the superclass from the subclass. In this case make your x protected.

Nikem
  • 5,716
  • 3
  • 32
  • 59
  • Right, so it's definitely impossible. Figured it was worth asking, if it was possible it'd probably be preferable. – Space Ostrich May 30 '16 at 05:23
  • You can add a protected setter to the base class and call that from the subclass, if you really feel that adds something. It probably doesn't add much, unless that protected setter validates the input or has a side-effect, e.g. logging. – tpdi May 30 '16 at 06:04
0

From Javadocs :The private modifier specifies that the member can only be accessed in its own class.

So no matter what, you can't access a private variable outside the IT'S class.

Nakul Kumar
  • 170
  • 2
  • 11
0

Variable with a private access modifier limits its visibility to that particular class. Despite the fact that your setter method is overridden to public, x is not accessible from another class(mySubClass). Overridden method is in mySubClass and x is not visible from mySubClass.

Nipun Thathsara
  • 1,119
  • 11
  • 20