java中矩形和圆形的周长面积_抽象类实现圆和矩形周长和面积的计算

Shape.class

package com.imooc;

public abstract class Shape

{

abstract void circumference(); //周长

abstract void area(); //面积

}

Rectangle.class

package com.imooc;

import java.util.Scanner;

public class Rectangle extends Shape

{

Scanner input=new Scanner(System.in);

int length=input.nextInt();

int width=input.nextInt();

@Override

void circumference()

{

System.out.println("矩形的周长是"+2*(length+width));

}

@Override

void area()

{

System.out.println("矩形的面积是"+length*width);

}

}

Circular.java

package com.imooc;

import java.util.Scanner;

public class Circular extends Shape

{

static double PI=3.14;

Scanner input=new Scanner(System.in);

int r=input.nextInt();

@Override

void circumference()

{

System.out.println("圆的周长是"+2*PI*r);

}

@Override

void area()

{

System.out.println("圆的面积是"+PI*r*r);

}

}

Test.java

package com.imooc;

public class Test

{

public static void main(String[] args)

{

System.out.println("请输入矩形的长和宽");

Shape rec=new Rectangle();

rec.circumference();

rec.area();

System.out.println("请输入圆的半径");

Shape cir=new Circular();

cir.circumference();

cir.area();

}

}

运行结果

请输入矩形的长和宽

7 8

矩形的周长是30

矩形的面积是56

请输入圆的半径

4

圆的周长是25.12

圆的面积是50.24

你可能感兴趣的:(java中矩形和圆形的周长面积)