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

246 Views Asked by At

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?

3

There are 3 best solutions below

2
Nikem On BEST ANSWER

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

0
Nakul Kumar On

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.

0
Nipun Thathsara On

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.