0

I'm trying to modify a value in a superclass from a subclass, and call that value from another subclass. For some reason when I do the value becomes null, or resets. I was working on a larger scale project, but ran into this problem and figured it'd be easier for everyone if I tested it in a smaller program. Here's what I've got:

public class Superclass { private int x; protected void setX(int n) { this.x = n; System.out.println(this.x); } protected int getX() { return this.x; } } public class Subclass extends Superclass { public void begin() { setX(55); Subclass2 subclass2 = new Subclass2(); subclass2.begin(); } } public class Subclass2 extends Superclass { public void begin() { System.out.println(getX()); } } public class Main { public static void main(String[] args) { Subclass subclass = new Subclass(); subclass.begin(); } } 

The superclass value successfully sets to 55, but when I call it from Subclass 2 it returns 0.

Thanks

1 Answer 1

2

You are instantiating a new object subclass2 here

public void begin() { setX(55); Subclass2 subclass2 = new Subclass2(); subclass2.begin(); } 

The x in subclass2 is not the same as the x in subclass. And since x is not initialized in Subclass2, a primitive int by default has a value of 0.

The value of x is 0 when you instantiate either Subclass or Subclass2. The x in subclass became 55 because you called begin() on subclass, which setX(55). During begin(), a totally different object subclass2 was created. subclass2's x is never touched. Therefore, calling begin() on subclass2 prints 0.

Sign up to request clarification or add additional context in comments.

4 Comments

But doesn't the X in the superclass stay the same, no matter what I instantiate?
No it doesn't stay the same. A value in a superclass is not a static value. It gets instantiated new every time you call its or one of its children's constructors.
Ah, ok thank you. How would I go about saving the Integer so I could call it then?
Are you asking how you can have a value on the class so it is shared by all instances of the class? If that's the case, what you want is a static variable. Like private static int x; There are plenty of resources to learn about those. Just Google something like "java static variable".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.