How can I change a superclass variable from a subclass?
In C ++, I could use 1 class in multiple files, and when I change a value with a function from one file, it changes that value globally.
In Java, every file must have its own class; when i change a value using a method from one file it doesn't change that value globally.
For example, in C ++, files might look like this:
someClass.h
class someClass{
private:
int x;
public:
//Constructor
someClass(){
x = 5;
}
void changeVariable(); //Declaring function for later
}
main.cpp
int main(){
someClass cClass;
cClass.changeVariable(); //Call function
cout << x; //outputs 6
}
fileA.cpp
void someClass::changeVariable(){
x = 6; //x is changed to 6 globally.
}
In Java:
someClass.java
public class someClass {
int x;
//Constructor
public someClass() {
x = 5;
}
main.java
public class main {
public static void main() {
someClass cClass = new someClass();
subClass cSub = new subClass();
cSub.changeVariable();
System.out.print(x); //outputs 5
}
}
fileA.java
public class fileA extends someClass {
void changeVariable() {
x = 6; //x is changed to 6 only for fileA
}
}
My question is how to change a variable from a subclass so that the variable changes globally (for Java). Sorry if the question is still confusing.
source to share
Try the following:
public class someClass {
static int x;
//Constructor
public someClass() {
x = 5;
}
That variable, where static means that its value is common to all objects of the same class. The fact that only one variable is created for everyone x
, and not one for each object.
Read this answer if you want it to explain well what static means:
source to share
No need for a static variable, this is the most equivalent thing you can do in Java:
public abstract class SomeClass {
protected int x = 5;
public abstract void changeVariable();
}
public class FileA extends SomeClass {
@Override
public void changeVariable() {
x = 6;
}
}
SomeClass
of course it doesn't have to be abstract
, but you'll have to implement it changeVariable
.
It also x
can't be private
, it must be protected
, so subclasses can be accessed.
source to share