手记

抽象类求图形周长和面积

Shape.java

package com.imooc.test;
public abstract class Shape {

   public abstract void girth();  //图形周长
  public abstract void area();   //图形面积
}

Rectangle.java

package com.imooc.test;
import java.util.Scanner;
public class Rectangle extends Shape {

Scanner in1 = new Scanner(System.in); 
float a = in1.nextFloat(); 

Scanner in2 = new Scanner(System.in);
float b = in2.nextFloat();

@Override
public void girth() {
    // TODO 自动生成的方法存根
    System.out.println("矩形的周长是:" + 2 * (a + b));
}

@Override
public void area() {
    // TODO 自动生成的方法存根
    System.out.println("矩形的面积是:" + a * b);
}

}

Circle.java

package com.imooc.test;
import java.util.Scanner;

public class Circle extends Shape {

Scanner in = new Scanner(System.in);
float r =in.nextFloat();

@Override
public void girth() {
    // TODO 自动生成的方法存根
    System.out.println("圆形的周长是:"+2*r*Math.PI);
}

@Override
public void area() {
    // TODO 自动生成的方法存根
    System.out.println("圆形的面积是:"+Math.PI*r*r);
}

}

ShapetTest.java

package com.imooc.test;
public class ShapeTest {
   public static void main(String[] args) {
    // TODO 自动生成的方法存根
    System.out.println("请输入矩形的长和宽");
    Shape one = new Rectangle();
    one.girth();
    one.area();
    System.out.println("请输入圆形的半径:");
    Shape two = new Circle();
    two.girth();
    two.area();
}

}
0人推荐
随时随地看视频
慕课网APP