報錯原文:Cannot make a static reference to the non-static method maxArea(Shape[]) from the type ShapeTestb
報錯原因:在一個類中寫了一個public void maxArea ()方法和一個main()方法,在main()方法中直接調用maxArea()方法就出現如題的錯誤。
解決方法,有兩種:
方法一、maArea()定義時加上修飾符static,即變為public static void maxArea(),即可在main()方法中正確調用。
public class ShapeTestb {
public static void main(String[] args) {
Shape[]shapes = new Shape[2];
maxArea(shapes);
}
//在main()中編譯錯誤
//public void maxArea(Shape[] shapes) {
//在main()中編譯正確
public static void maxArea(Shape[]shapes) {
…………
}
}
方法二、先實例化類,然后通過對象調用maxArea()方法也行。
public class ShapeTestb {
public static void main(String[] args) {
Shape[] shapes = new Shape[2];
ShapeTestb st = new ShapeTestb();
st.maxArea(shapes);
}
public void maxArea(Shape[] shapes) {
…………
}
}