简体   繁体   English

在java中不使用类型(类名)创建新实例

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

I found this code.我找到了这个代码。 Now I'am puzzled, what origin = new Point(0, 0);现在我很困惑,什么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.如果它是一个为什么使用new的赋值。

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);线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?基本上是将变量origin设置为 x 和 y 都设置为 0 的 Point 对象。现在我认为您感到困惑的是为什么会出现这种情况? 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.在我们的例子中, origin变量被设置为类 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.第二个我们这样做的原因是因为在 Java 中你可以声明一个不带任何参数的对象,当 Java 看到没有给定参数时,它会调用默认构造函数。 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).它基本上存储两个值(x 和 y)。 That's the simple explanation.这就是简单的解释。

origin = new Point(0, 0) sets the value of the variable origin origin = new Point(0, 0) 设置变量origin的值

the not so simple explanation is that Point is a class.不那么简单的解释是 Point 是一个类。 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 origin 是该类的对象,此行运行该类的构造函数,该构造函数将该对象中的两个变量的值设置为 0 和 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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