How to initialize objects already declaring values?

4

For example in this code:

public class Main
{
    public static void main(String[] args)
   {
            Point p = new Point();
    }
}

class Point
{
    int x;
    int y;
}

Is there a way to declare values to x and y already while running new ?

    
asked by anonymous 14.01.2017 / 19:40

1 answer

6

You can try this by creating a constructor that receives the parameters and assigning them as follows:

class Point {
    private int x;
    private int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

Then, just start by passing the values:

Point p = new Point(4, 8);
    
14.01.2017 / 19:43