How to initialize objects already declaring values?

Asked

Viewed 57 times

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;
}

There is a way to declare values to x and y while executing the command new?

1 answer

6


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

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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.