簡體   English   中英

Java 未使用重載方法

[英]Java overload method not used

我有這個活動,我需要編寫一個重載方法來計算正方形、圓形、梯形和三角形的面積。 要求用戶輸入邊長、底邊、垂直高度和半徑的值。 使用方法名稱 AREA()。 這是我嘗試過的代碼,但我總是得到已定義的錯誤方法。 我試圖更改參數的一種數據類型,但沒有收到錯誤,但是當我嘗試運行程序時,只使用/調用了一種方法。

import java.util.*;
import java.lang.*;

public class Method
{
 static double getSides() 
{
 double sides;
 System.out.print("Input sides here: ");
 sides = input.nextDouble();
 return sides;
 }
 static double getRadius() 
 {
 double radius;
 System.out.print("Input radius here: ");
 radius = input.nextDouble();
 return radius;
 }
 static double getBase() 
 {
 double base1;
 System.out.print("Input base 1: ");
 base1 = input.nextDouble();
 return base1;
 }
 static double getUpperBase() 
 {
 double base2;
 System.out.print("Input base 2: ");
 base2 = input.nextDouble();
  return base2;
 }
 static double getHeight() {
 double height;
 System.out.print("Input height: ");
 height = input.nextDouble ();
 return height;
 }
 static double AREA(double sides){
 return(sides * sides);
 }
 static double AREA(double radius){
 return (Math.PI * radius * radius);
 }
 static double AREA(double base1, double height){
 return (0.5 * base1 * height);
 }
 static double AREA(double base1, double base2, double height){
 return (0.5 * (base1+base2)* height);
 }
 static Scanner input = new Scanner (System.in);
 public static void main(String[] args) {
 double sides, radius, base1, base2, height;
 sides = getSides ();
 radius = getRadius ();
 base1 = getBase ();
 base2 = getUpperBase ();
 height = getHeight ();
 System.out.printf ("\nThe area of the square is: %.4f", AREA(sides));
 System.out.printf ("\nThe area of the circle is: %.4f", AREA(radius));
 System.out.printf ("\nThe area of the triangle is: %.4f", AREA(base1,
height));
 System.out.printf ("\nThe area of the trrapezoid
 is: %.4f", AREA(base1,
base2, height));
 }
}

您的想法沒有問題,但是當您嘗試在 java 中實現方法重載時存在編譯器限制。由於您使用的 arguments 具有相似的數據類型相同的返回類型,因此這兩個函數會產生問題:

static double AREA(double sides){
 return(sides * sides);
 }
 static double AREA(double radius){
 return (Math.PI * radius * radius);
 }

其他兩個重載函數沒問題,因為您通過不同數量的參數來區分它們。 記住你可以使用

  1. 不同數量的參數
  2. 更改參數順序
  3. 當您嘗試實現方法重載時,方法參數的不同數據類型可以區分兩種方法。

您可以使用的另一種方法是創建一個抽象方法returnType Area( datatype parameter1 , datatype parameter2 ) 並繼承。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM