gpt4 book ai didi

java - 从另一个类调用方法时遇到问题

转载 作者:行者123 更新时间:2023-11-30 03:55:24 26 4
gpt4 key购买 nike

下面是我的类文件 Rectangle 和带有 main 方法的类文件 testRectangle 。现在,在 testRectangle 中,当我调用“矩形”类中的“周界”方法时,我收到一条错误消息。我收到的错误消息指出,“将‘perimeter()’的修饰符更改为‘static’。该方法不能是静态的,因为我在主方法中将有几个不同的矩形对象。我做错了什么吗?有任何帮助吗?不胜感激。

矩形.java

public class Rectangle {
private int length;
private int width;

Rectangle(int len, int wid) {
length = len;
width = wid;
}
public int perimeter(Rectangle rec){
int p = 2*length + 2* width;
return p;
}
}

testRectangle.java

    public class testRectangle {

public static void main(String[] args) {
Rectangle r1 = new Rectangle(5,4);
int r1Perimeter = Rectangle.perimeter(r1);
//the line above this is where I get the error message
//the red squiggly line goes under "Rectangle.perimeter(r1);
}

}

最佳答案

您必须在 Rectangle 对象上调用该方法。因为,perimeter() 是一个实例方法,所以您必须调用一个实例。

如果perimeter()是一个静态方法,那么你可以用Class来调用它,比如Rectangle.perimeter(r1);

int r1Perimeter = r1.perimeter(r1);

并且不需要在那里传递 Rectangle 对象,定义如下 perimeter() 方法

public int perimeter(){
int p = 2*length + 2* width;
return p;
}

关于java - 从另一个类调用方法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23353284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com