定义一个抽象类图形Shape类,由该派生出两个子类圆Circle类和矩形Rectangle类。Shape里声明了抽象方法area(),该方法分别在两个子类里得到实现。
程序参考运行效果图如下:
任务分析:
1、定义一个抽象类Shape,在它里面创建抽象方法area()方法
2、它的子类Circle类和Rectangle类
- 子类Circle类:
属性: r(圆的半径)
方法:
- 创建带参构造函数(参数为r)
- 重写area()方法,要求在里面返回圆的面积
- Rectangle类:
属性:length(长)和wide(宽)
方法:
- 创建带参(length和wide为参数)构造方法
- 重写area()方法,要求在里面返回矩形的面积
3、编写测试类,分别创建Circle类的对象和Rectangle类的对象,设置圆的半径以及矩形的长宽,输出圆的面积和矩形的面积。(具体输出结果以具体设定参数为准)
package me.feihong.shape;
public abstract class Shape {
public Shape() {
}
public abstract double area();
}
package me.feihong.shape;
public class Circle extends Shape {
private double r;
public Circle() {
}
public Circle(double r) {
this.r=r;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
@Override
public double area() {
double area=Math.PI*r*r;
return area;
}
}
package me.feihong.shape;
public class Rectangle extends Shape {
private double length;
private double wide;
public Rectangle() {
}
public Rectangle(double length,double wide) {
this.length=length;
this.wide=wide;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWide() {
return wide;
}
public void setWide(double wide) {
this.wide = wide;
}
@Override
public double area() {
double area=length*wide;
return area;
}
}
package me.feihong.test;
import me.feihong.shape.Circle;
import me.feihong.shape.Rectangle;
public class Test {
public static void main(String[] args) {
//创建类的实例,并分别对圆的半径和矩形的长宽进行赋值
Circle cir=new Circle(3);
Rectangle rect=new Rectangle(5,6);
//调用area()方法,输出结果
System.out.println("圆的面积为"+cir.area());
System.out.println("矩形的面积为"+rect.area());
}
}
输出结果:
圆的面积为28.274333882308138
矩形的面积为30.0
1 条评论
想想你的文章写的特别好