NEW OBJECT IS OVERRIDING ANOTHER OBJECT VARIABLE

Royce Roy

Total Post:149

Points:1043
Posted by  Royce Roy
Java  OOPS 
 555  View(s)
Ratings:
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
      } 
   }
}
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: New Object is overriding another Object variable

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!