簡體   English   中英

我應該如何在 if/else 語句中的單個構造函數中傳遞“類型”參數?

[英]How should I pass the “type” parameter of in a single constructor in an if/else statement?

我應該如何在 if/else 語句中傳遞構造函數的“類型”參數? 例如 - cal(2,2,0,rectangle)。 因此,如果 type=rectangle 則計算矩形的面積。 如果 type=circle,則計算圓的面積。

我正在使用單個構造函數。 我的問題是我知道邏輯,但我不能用語法來寫。 我正在使用 Java 或 Apex。

我想使用 if-else 語句。 我應該如何在代碼中傳遞類型參數?

我的程序是這樣的——

  1. 如果“type”=square,編譯器將調用計算正方形的面積。

  2. 如果“type”=circle,編譯器將調用計算圓的面積。


   public class Area {
      
      private String type;
      private Integer length;
      private Integer breadth;
      private Integer height;
      private Integer area;
      
     public void setType(String t){
          type=t;    
      }
      public void setLength(Integer l){
          length=l;    
      }
      public void setbreadth(Integer b){
          breadth=b;    
      }
      public void setheight(Integer h){
          height=h;    
      }
     /* public void setArea(Integer a){
          area=a;    
      } */
  
      public Integer getLength(){
          return length;  
      }
      public Integer getbreadth(){
          return breadth;  
      }
      public Integer getheight(){
          return height;  
      }
      public string gettype(){
          return type;  
      }
      
      public Integer AreaRectangle(){
          return area=length*breadth;
      }
      
      public Integer AreaSquare(){
          return area=length*length;
      }
      
      public integer AreaTriangle(){
          return area=1/2 *(breadth*height);
      }
      
     public Area(){ // default constructor
         length=9;
          breadth=2;
          height=7;       
                  
      }
      public Area(String t,Integer l ,Integer b,Integer h ){         // parameterised constructor
          type=t;
          length=l;
          breadth=b;
          height=h;
                 
      }  
  }

你沒有。 您創建了一個名為 shape 的抽象類。

public abstract class Shape {
    abstract double area();  
}

然后是另外兩個擴展Shape類,每個類都提供了正確的實現

public class Square extends Shape {
    private int side;
    public Square(int side) {
        this.side = side;
    }
    public double area() {
        return (double) side * side;
    }
}

現在在你想調用它的地方:

Shape shape = new Square(5);
double area = shape.area();

Int radius = 4;
shape = new Circle(radius);
double circle area = shape.area();

暫無
暫無

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

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