我是 Java 编程新手。我有三个类,分别是 Main
、Point
和 Rectangle
。我可以使用 Rectangle
类中的所有构造函数,除了这个:Rectangle(Point p, int w, int h)
。 Java 编译器给出:“无法解析构造函数 'Rectangle(java.awt.Point, int, int)'”错误。谢谢。
这是我的类(class):
Main.java
import java.awt.*;
import java.awt.Point;
import java.awt.Rectangle;
public class Main {
public static void main(String[] args) {
Point originOne = new Point(5,10);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
}
}
点.java
public class Point {
public int x = 0;
public int y = 0;
//contructor
public Point(int a, int b){
x = a;
y = b;
}
}
矩形.java
public class Rectangle {
public Point origin;
public int width = 0;
public int height = 0;
//four contructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p){
origin = p;
}
public Rectangle(int w, int h){
origin = new Point(0,0);
width = w;
height = 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 rectangle
public int getArea() {
return width * height;
}
}
最佳答案
你的答案相当简单。您导入了错误的导入,而不是导入 java.awt.Rectangle
,而是导入您自己的类。
通过这样做:
import <nameOfTheProject>.Rectangle;
如果我在 Eclipse 中有一个名为 MyShapes 的项目并且有相同的类。我会像这样导入它:
import MyShapes.Rectangle;
现在这显然取决于您的文件结构,但如果它位于子文件夹(子包)内,我会喜欢:
import MyShapes.ShapesClasses.Rectangle;
如果您计划使用自己的 Point 类而不是 Java.awt 的 Point 类,这也适用于 Point 类!
关于Java - 无法解析构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63373472/