javaprivateabstractiondatafield

How to use abstract methods to set a private data field?


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?


Solution

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