Java 定义接口Shape,设计矩形、圆、圆柱体等类实现Shape接口,分别创建代表矩形、圆、圆柱体的3个对象存入一个Shape类型的数组,并通过调用size()方法将数组中各类图形的大小输出。

Java 定义接口Shape

其中包括一个方法size(),设计矩形、圆、圆柱体等类实现Shape接口,其size()方法分别表示计算矩形面积、圆面积、圆柱体体积。分别创建代表矩形、圆、圆柱体的3个对象存入一个Shape类型的数组,并通过调用size()方法将数组中各类图形的大小输出。

接口:

public interface Shape {
 
 double size();
 
}

标准类:

public class Orthogon implements Shape{
 private double a;
 private double b;
  //K.kuimeng
public double getA() {
  return a;
 }
 public void setA(double a) {
  this.a = a;
 }
 public double getB() {
  return b;
 }
 public void setB(double b) {
  this.b = b;
 }
 
 @Override
 public double size() {
  // TODO Auto-generated method stub
  //K.kuimeng
  return getA()*getB();
 }
 @Override
 public String toString() {
  return "矩形面积="+size();
 }
 }

 class Roundness implements Shape{
 private double r;

public double getR() {
  return r;
 }
 public void setR(double r) {
  this.r = r;
 }
 @Override   //K.kuimeng
 public double size() {
  // TODO Auto-generated method stub
  return 3.14*getR()*getR();
 }
 @Override
 public String toString() {
  return "圆面积="+size();
 }
 }

class Cylinder implements Shape{
  private double r;
  private double h;
  
  public double getR() {
   return r;
  }
  public void setR(double r) {
   this.r = r;
  }
  public double getH() {
   return h;
  }
  public void setH(double h) {
   this.h = h;
  }

@Override
  public double size() {
   // TODO Auto-generated method stub
   return 3.14*r*r*h;
  }
  @Override   //K.kuimeng
  public String toString() {
   return "圆柱体体积="+size();
  } }

测试类:

import java.util.Arrays;

public class ShapeTest {
 Shape[] e;
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Orthogon orthogon=new Orthogon();
  orthogon.setA(2);
  orthogon.setB(2);

Roundness roundness=new Roundness();
  roundness.setR(2);
  
  Cylinder cylinder=new Cylinder();
  cylinder.setH(2);
  cylinder.setR(2);   //K.kuimeng

ShapeTest s1=new ShapeTest();  
  s1.e=new Shape[] {orthogon,roundness,cylinder};  
  System.out.println(Arrays.toString(s1.e));
  }}

运行结果:

[矩形面积=4.0, 圆面积=12.56, 圆柱体体积=25.12]

喜欢博主代码的朋友记得点赞关注博主哟~

你可能感兴趣的:(java,Java小白必学题)