※J.Y Chen 的個人部落格 ※

Just Follow Our Heart And We will shine!

112 瀏覽人次

【程式語言】JAVA的第十一堂課 |物件導向程式設計 介面 implements

Published: in JAVA by .

ch11.java

class ch11
{
 public static void main(String[] aa)
 {
   
    CCircle c=new CCircle("Red",6);
   
    c.show(); // this is a red circle
    CRect r=new CRect(6,8);
    r.show();


    CShape c1=new CCircle("Red",8);
    c1.show();

    CShape[] ca=new CShape[5];
        
    ca[0]=new CCircle("blue",7);
    ca[1]=new CCircle("Red",6);
    ca[2]=new CRect(5,2);
    ca[3]=new CRect(6,8);
    ca[4]=new CCircle("blue",9);
 
    int im=0;
    double max=0;
    for(int i=0;i<5;i++)
    {
		if (ca[i].area() > max ){
			max = ca[i].area();
			im = i;
		}
    }
    System.out.println("ca["+im+"] has the max area="+max);
 }
}

CShape.java

abstract class CShape implements GeoProp
{
  protected String color;
  CShape(String s)
  {
      color=s;
  }
  void setColor(String s)
  {
     color=s;
  }

}

interface GeoProp {
	abstract void show();
	abstract double area();
}

CCircle.java

class CCircle extends CShape implements GeoProp
{
  private double radius;
  CCircle(String s, double r) {
    super(s);
    radius=r;
  }
  
  public double area() {
	return radius*radius*3.14;
  }
  
  public void show()
  {
     System.out.println("This is a "+color+" color r="+radius+" circle");
  }

}

CRact.java

class CRect extends CShape implements GeoProp
{ 
  private double length;
  private double width;
  
  CRect(double l, double w)
  {
    super("none");
    length=l;
    width=w; 
  }
  public double area(){
	  return length * width;
  }
  public void show()
  {
     System.out.println("This is a "+color+" color rectangle");
  }
}

RESULT:

©2019 - 2024 Henry Chen