赞
踩
题目 1.
题目 2.
- 为了克服Java单继承的缺点,Java使用了接口
- 接口可以用来描述一种抽象。
- 接口可以用来实现解耦。
接口在java中是一种类似于抽象方法的集合
建立一个AreaInterface接口,定义功能为求图形面积
- public interface AreaInterface {
- double PI = Math.PI;
- double area();
- }
建立长方形类,定义他的长和宽,并求出面积
- public class Rectangle implements AreaInterface{
- // 长方形的长x
- private double x;
- // 长方形的宽y
- private double y;
-
- public Rectangle(double x, double y) {
- this.x = x;
- this.y = y;
- }
-
- public Rectangle() {
- }
-
- @Override
- public String toString() {
- return "该长方形面积为:" + area();
- }
-
- @Override
- public double area() {
- return x*y;
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
这里要注意,重写接口声明的方法时:
实现接口时,也要注意:
再运用主类测试,看看接口方法是否被调用
- public class TestArea {
- public static void main(String[] args) {
- Rectangle rectangle = new Rectangle(10.0,20.0);
- System.out.println(rectangle.toString());
- }
- }
结果如下:
根据题目要求,建立了Shape接口
- public interface Shape {
- public double area();
-
- }
同样,分别建立Circle,Square,Traingle类
- public class Circle implements Shape{
- private double r;
-
- public Circle(double r) {
- this.r = r;
- }
-
- public Circle() {
- }
-
- @Override
- public double area() {
- return Math.PI * r * r;
- }
-
- @Override
- public String toString() {
- return "圆的面积为" + area();
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public class Square implements Shape{
- // 定义正方形的边长x
- double x;
-
- public Square(double x) {
- this.x = x;
- }
-
- @Override
- public double area() {
- return x * x;
- }
-
- public Square() {
- }
-
- @Override
- public String toString() {
- return "正方形的面积为" + area();
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public class Triangle implements Shape{
- private double a ,b ,c;
- private double p;
- @Override
- public double area() {
- return Math.sqrt(p*(p-a)*(p-b)*(p-c));
- // 海伦公式求三角形面积
- }
-
- public Triangle(double a, double b, double c) {
- this.a = a;
- this.b = b;
- this.c = c;
- p = (a+b+c)/2;
- }
-
- public Triangle() {
- }
-
- @Override
- public String toString() {
- return "三角形的面积为" + area();
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- import java.util.concurrent.TransferQueue;
-
- public class TestArea {
- public static void main(String[] args) {
- System.out.println("------[题目1]------");
- Rectangle rectangle = new Rectangle(10.0,20.0);
- System.out.println(rectangle.toString());
- System.out.println("------[题目2]------");
- Circle circle = new Circle(4.0);
- System.out.println(circle.toString());
- Square square = new Square(3.0);
- System.out.println(square.toString());
- Triangle triangle = new Triangle(3,4,5);
- System.out.println(triangle.toString());
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
结果如下
- 理解抽象类和接口的联系和区别
- 掌握接口的继承与实现
- 进一步体会复杂系统中如何设计和使用抽象类和接口。
完成了以上三点,并且多注意在实现接口时的一些事项。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。