问答详情
源自:10-3 Java 中的抽象类

小白请教怎样简化?

package com.imooc;


public abstract class Shape {

public abstract double perim();

public abstract double area();

-----------------------------------------------

public class Rectangle extends Shape {

double a=5.2;

double b=2.3;

double c=0;

double d=0;

@Override

public double perim() {

c=(a+b)*2;

System.out.println("矩形的周长:"+c);

return c;

// TODO Auto-generated method stub

}


@Override

public double area() {

d=a*b;

System.out.println("矩形的面积:"+d);

return d;

// TODO Auto-generated method stub

-------------------------------------------------------------

public  class Circle extends Shape {

double e=3.14;

double r=2.5;

double j=0;

double i=0;

@Override

public double perim() {

j=2*e*r;

System.out.println("圆形的周长:"+j);

// TODO Auto-generated method stub

return j;

}


@Override

public double area() {

i=e*r*r;

System.out.println("圆形的面积:"+i);

// TODO Auto-generated method stub

return i;

}

-----------------------------------------------------

public class man {


public static void main(String[] args) {

// TODO Auto-generated method stub

       Shape pe1 = new Rectangle();

       pe1.perim();

       pe1.area();

       Shape pe2 = new Circle();

       pe2.perim();

       pe2.area();

       

}

--------------------------

矩形的周长:15.0

矩形的面积:11.959999999999999

圆形的周长:15.700000000000001

圆形的面积:19.625


提问者:慕勒8415117 2018-10-16 18:06

个回答

  • 慕沐736890
    2018-10-16 20:06:04
    已采纳

    楼主可以看一下我的代码,如果只是为了输出周长、面积,而不对其进行后续的修改、访问,可以不用定义c、d、i、j,求面积和求周长函数也可以使用void类型

    https://img2.mukewang.com/5bc5d2b0000140d606680831.jpg