请看一下下面的代码片段,我在阅读关于创建对象的java教程时偶然发现了这段代码。
// Declare and create a point object and two rectangle objects.
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);
rectOne
对象是通过传递Point
类的对象,即矩形的originOne
、width
和height
来创建的。如果你看一下Rectangle
类的文档,你会发现文档中没有这样的构造函数接受三个参数(即a点、宽度和高度)。然而,也有单独的构造函数,其中一个构造函数将类Point
的一个点作为参数
Rectangle(Point p)
另一个以矩形的宽度和高度作为参数
Rectangle(int width, int height)
我想知道你能像我在教程中分享的代码片段那样组合构造函数吗?
在本例中,您不使用java.awt.Rectangle
。在本教程中,他们使用了Rectangle类的一个自己的实现,该类具有这样的构造函数。
组合构造函数?Java
中没有这样的东西。你可以转换
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
至
Rectangle rectOne = new Rectangle(new Point(23, 94), 100, 200);//not a Combining.
矩形已经有一个接受Point的构造函数。
不,您不能按照建议的方式组合两个构造函数。矩形有一个3个参数的构造函数:
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
您在文档链接中引用的Rectangle类与教程中使用的类无关。
您可以从另一个构造函数调用一个构造函数。例如,一个有3个参数的构造函数可以首先调用一个只有前两个参数的构造器,然后初始化第三个参数。
例如,Rectangle构造函数可以重写为:
public Rectangle(Point p, int w, int h) {
this (p);
width = w;
height = h;
}
或
public Rectangle(Point p, int w, int h) {
this (w,h);
origin = p;
}
不,你不能。只能使用已经按原样定义的构造函数。最好的方法是使用最适合您的用例的构造函数,并使用setter方法来分配您的附加属性。
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne);
rectOne.setSize(100, 200);
或
Rectangle rectOne = new Rectangle(originOne.getX(), originOne.getY(), 100, 200);
或
Dimension dimension = new Dimension(100, 200);
Rectangle rectOne = new Rectangle(originOne, dimension);
这取决于您:)
Rectangle提供了7个构造函数,它们具有类型为int
、Point
和Dimension
的不同参数。不幸的是,没有构造函数按照您的要求将int
与Point
或Dimension
混合。
相反,您有以下选项:
-
只传递int(通过从点获取)
Point originOne = new Point(23, 94); Rectangle rectOne = new Rectangle(originOne.x, originOne.y, 100, 200);
-
传递维度作为第二个参数
Point originOne = new Point(23, 94); Dimension sizeOne = new Dimension(100, 200); Rectangle rectOne = new Rectangle(originOne, sizeOne);
对于没有原点的矩形,可以使用
Dimension sizeTwo = new Dimension(50, 100);
Rectangle rectTwo = new Rectangle(sizeTwo);
通过这种方式,您甚至可以轻松地重用不同矩形的原点或大小。