JAVA – Need help with validation in constructor

Code with C | Programming: Projects & Source Codes Forums JAVA Programming JAVA – Need help with validation in constructor

This topic contains 2 replies, has 1 voice, and was last updated by  CWC 6 months, 2 weeks ago.

  • Author
    Posts
  • #12689

    CWC
    Keymaster

    I have this constructor called MovablePoint with these fields (x:int, y:int, xSpeed:int, ySpeed:int).

    I also have an interface with 2 fields with the limits of a plain PLAIN_X_MAX = 1000 and PLAIN_X_MIN = -1000. Value X should be within these 2 when creating the object.

    How should I validate X in the constructor before constructing this.X , so that when instatiating the Object, it can only be instantiated if value of X is within the range of PLAIN_X_MAX and PLAIN_X_MIN ?

    I tried with checked exception created by me, PointOutOfBounds which extends Exceptions. Tried something, but whatever value I input for X when doing new MovablePoint( X, Y, xSpeed, ySpeed); I always get that exception.

  • #12690

    CWC
    Keymaster

    I hope my pseudo code helps?

  • #12691

    CWC
    Keymaster

    If you call a constructor, you are already instanciating your object so, it is too late to avoid this fact. You should make a test on X before to decide if you can finally create your object. It can be like this

    Or if you want use a class constructor, you can create a child class for MovablePoint which will call the mother constructor if the conditions are relevant...

    You can also use a static method inner the class MovablePoint to validate the condition

    If you absolutely want to use the constructor, you can call the protected void finalize() method but, the object will be necessary created before to be destroyed and as you can not really decide when an object is effectively destroyed it will remain in memory until the garbage collector does the job.

You must be logged in to reply to this topic.