简体   繁体   中英

Creating new instance without using type (class name) in java

I found this code. Now I'am puzzled, what origin = new Point(0, 0); means. If it is instantiation/object creation where is type (class name) preceding it. If it is an assignment why new is used.

public class Rectangle {
    public int width = 0;
    public int height = 0;
    public Point origin;

    //Four constructors
    public Rectangle() {
        origin = new Point(0, 0);
    }

    public Rectangle(Point p) {
        origin = p;
    }

    public Rectangle(int w, int h) {
        this(new Point(0, 0), w, h);
    }

    public Rectangle(Point p, int w, int h) {
        origin = p;
        width = w;
        height = h;
    }

    //A method for moving the rectangle
    public void move(int x, int y) {
        origin.x = x;
        origin.y = y;
    }

    //A method for computing the area of the rectangle
    public int area() {
        return width * height;
    }
}

To answer this question in the simplest way:

The line origin = new Point(0, 0); is basically setting the variable origin to a Point object with x and y both set to 0. Now I think what you are confused on is why this is even there? First we need to look where it's declared. Every object has a constructor, whether it's an empty constructor of one that sets some variables to a default value (Like in this case!). In our case origin variable is being set to a default value inside the default constructor of the class Rectangle. Second the reason why we are doing this is because in Java you can declare an object without any arguments, when Java sees that no arguments are given, it will call the default constructor. In the default constructor it's highly recommended to define important variables that will be used in the object. I hope this helps! =)

Point is type of variable. It basically stores two values(x and y). That's the simple explanation.

origin = new Point(0, 0) sets the value of the variable origin

the not so simple explanation is that Point is a class. origin is an object of that class and this line runs the constructor of this class that sets the value of the two variables in that object to 0 and 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM