1. 按照下列要求完成接口的设计。
(1)定义一个public接口Shapes,其包名为oop.base;
(2)定义返回值为double类型并且无输入参数的public抽象方法,其中方法名为getArea;
(3)定义返回值为double类型并且无输入参数的public抽象方法,其中方法名为getPerimeter。
2. 按照下列要求完成类实现接口的设计。
(1)定义一个public类Square,其包名为oop.base,且该类实现了第1题中的接口Shapes;
(2)在类Square中定义两个double类型的public成员变量,其中成员变量名为:width,height;
(3)用带有两个形式参数的public构造方法对Square类中的成员变量进行初始化,其中形式参数名为:width,height;
(4)在Square类中实现getArea方法,返回面积,width* height;
(5)在Square类中实现getPerimeter方法,返回周长,2*(width+height)。
3. 在第1题和第2题的基础之上,写出下列程序的执行结果,并用程序验证。
package oop.base.test;
import oop.base.Square;
public class SquareTest {
public static void main(String[] args) {
Square squ = new Square(5, 15);
double area = squ.getArea();
double peri = squ. getPerimeter();
System.out.print("area:" + area + " peri:" + peri);
}
}
源代码:
package haut.oop.exp2.exten;
import haut.oop.exp2.abstr.Square;
import java.util.*;
interface Shape{ //接口
double getArea();
double getCircumference();
}
abstract class Rectangle implements Shape{
public double width,height;
public Rectangle(double width,double height){
this.width = width;
this.height = height;
}
public double getArea(){
double area = width * height;
return area;
}
public double getPerimeter(){
return 2*(width + height);
}
public static void main(String[] args) {
Square squ = new Square(5, 15);
double area = squ.getArea();
double peri = squ. getPerimeter();
System.out.print("area:" + area + " peri:" + peri);
}}
截屏效果:

本文设计了一个形状接口Shapes及其实现类Square,Square类通过构造函数初始化宽度和高度,并实现了计算面积和周长的方法。

被折叠的 条评论
为什么被折叠?



