Sam
Sam

Reputation: 31

Modifying value of superclass through subclass, and calling the value of the superclass in another subclass

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

Upvotes: 0

Views: 48

Answers (1)

Hanchen Jiang
Hanchen Jiang

Reputation: 2682

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.

Upvotes: 2

Related Questions