0

In my app I have two classes:

public class A  
{
    public final int value;
 
    A(int value)
    {
        this.value = value;
    } 
}
 
public class Mutable_A  
{
    public int value;
 
    A(int valule)
    {
        super(a);
        this.value = value;
    } 
}

and in the code I do this:

 A a = new Mutable_A(50);
 ...
 ((Mutable_A) a).value = 60;
 ...
 if (A.value == 60)
 {
     print "I'm 60";
 } else {     
     print "I'm 50";    
 }     
 

Theorically a.value is 60, but due to I declare a as a A variable (instead of a Mutable_A variable), the value of a.value is 50.

Is there a way to correct this?

The Matrix
  • 1,268
  • 2
  • 14
  • 23
  • I assume you meant MutableA to **extend** Mutable? Please always provide true [mcve], not some pseudo code you consider meaningful. – GhostCat Aug 13 '20 at 10:53
  • Beyond that see: https://stackoverflow.com/questions/12086298/why-is-an-instance-variable-of-the-superclass-not-overridden-by-a-subclass ... – GhostCat Aug 13 '20 at 10:54
  • 1
    The only answer is: there is no real inheritance for fields. Simply: dont do it. – GhostCat Aug 13 '20 at 10:55
  • It is not possible to use another class as a constructor. Do you mean it extends class A. If it does then instance variables are not overridden. So this should not be a problem. Share a running code if possible. – Ishita Singh Aug 13 '20 at 10:56
  • Not only is there no inheritance for fields, but there is no overriding for 'final'. So that's two reasons for "don't do it", – user13784117 Aug 13 '20 at 10:57
  • Mutable_A extends A. The difference BTW A and Mutable_A is only one: A defines a final variable and Mutable_A defines the same variable but not final. – The Matrix Aug 14 '20 at 11:03

1 Answers1

0

When you create an object of Mutable_A, it stores two variables called value.

Initially you set both variables to 50. Then you change the one declared in Mutable_A class to 60.

End result: One variable is set to 50 and the other is set to 60. This is the expected behavior.

It sounds like you want to use only the variable declared in Mutable_A. You can achieve that by adding a get method that can be overridden:

public class A  
{
    private final int value;
 
    A(int value)
    {
        this.value = value;
    } 
    int getValue() { return this.value; }
}
 

public class Mutable_A  
{
    private int value;
 
    A(int valule)
    {
        super(a);
        this.value = value;
    } 

    void setValue(int value) { this.value = value; }
    int getValue() { return this.value; }
}

Now, a.getValue() will return the updated value, because you end up calling the overridden method:

((Mutable_A) a).setValue(60);
if (a.getValue() == 60) {
    // will enter here

That said, this isn't great design, because you have two copies of the variable with the same name and it may not be easy to know which one gets used where.

Joni
  • 108,737
  • 14
  • 143
  • 193