“Cannot make a static reference to the non-static method”處理方法


報錯原文: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) {
              …………
       }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM