提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
题目:
任务:通过图形类的计算面积的方法,计算矩形和三角形的面积。
编程要求
仔细阅读右侧编辑区内给出的代码框架及注释,在 Begin-End 中计算矩形和三角形的面积,具体要求如下:
-
将 Shape 图形类改为抽象类,并定义一个抽象方法 area(),返回值类型为 double,计算图形的面积;
-
Rectangle 为矩形类,该类继承 Shape 类,并拥有 Shape 类的属性,重写抽象方法 area,计算矩形的面积(高*宽),并将计算结果返回;
-
Triangle 为矩形类,该类继承 Shape 类,并拥有 Shape 类的属性,重写抽象方法 area,计算三角形的面积(高*宽/2),并将计算结果返回。
代码:
Shape.java文件
/**
* 通过图形类的计算面积的方法,计算矩形和三角形的面积。
*/
// 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
/********** Begin **********/
// 将 Shape 类改为抽象类
abstract public class Shape {
public int width; // 几何图形的宽
public int height; // 几何图形的高
public Shape(int width, int height) {
this.width = width;
this.height = height;
}
abstract public double area();
// 定义一个抽象方法 area(),返回值类型为 double,计算图形的面积
}
// Rectangle 为矩形类,该类继承 Shape 类,并拥有 Shape 类的属性
class Rectangle extends Shape {
public Rectangle(int width,int height)
{
super(width,height);
}
// 定义一个有参构造器
public double area()
{
return width*height;
}
// 重写抽象方法 area,计算矩形的面积(高*宽),并将计算结果返回
}
// Triangle 为矩形类,该类继承 Shape 类,并拥有 Shape 类的属性
class Triangle extends Shape{
public Triangle(int width,int height)
{
super(width,height);
}
// 定义一个有参构造器
public double area()
{
return width*height/2;
}
// 重写抽象方法 area,计算三角形的面积(高\*宽/2),并将计算结果返回
}
/********** End **********/
Demo.java文件
public class Demo {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 4);
System.out.println("矩形的面积为:" + rectangle.area());
Triangle triangle = new Triangle(2, 5); // 创建三角形类对象
System.out.println("三角形的面积为:" + triangle.area());
}
}
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了Java继承和多态之abstract类。