Home > DeveloperSection > Forums > New Object is overriding another Object variable
Royce Roy
Royce Roy

Total Post:134

Points:938
Posted on    December-27-2015 11:36 PM

 Java Java  OOPS 
Ratings:


 1 Reply(s)
 279  View(s)
Rate this:
I have created two Function objects, the values in the first get overwritten with the values assigned to the second object.
What is wrong in this approch?

public class Function { 
private static double coefficient;
private static int startX;
private static int endX;
private static int exponent;

protected Function(double coefficient, int startX, int endX, int exponent) {
    this.coefficient = coefficient;
    this.startX = startX;
    this.endX = endX;
    this.exponent = exponent;
  }  
    public static void main(String[] args) {
    Function func1 = new Function(2, 1, 2, 2); 
    Function func2 = new Function(0,1,2,1/3);
    // now func1 properties are the same as func2
      } 
   }
}


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    December-27-2015 11:42 PM

Hey Royce, Modify your code as below:
public class Function { 
private double coefficient;
private int startX;
private int endX;
private int exponent;

protected Function(double coefficient, int startX, int endX, int exponent) {
    this.coefficient = coefficient;
    this.startX = startX;
    this.endX = endX;
    this.exponent = exponent;
  }  
    public static void main(String[] args) {
    Function func1 = new Function(2, 1, 2, 2); 
    Function func2 = new Function(0,1,2,1/3);
    // now func1 properties are the same as func2
      } 
   }
}
The code you have done , you are making static variables which are only created once for the application. So, every time it overrides the value.

Don't want to miss updates? Please click the below button!

Follow MindStick