接口
一、什么是接口?
接口与抽象类相似,但接口中只包含常量和抽象方法。接口的目的是指明相关或不相关类的多个对象的共同行为。
同样也不能使用new操作符创建接口的实例。
定义接口:
修饰符 Interface 接口名 {
//常量声明
//抽象方法签名
}
类和接口之间的关系称为接口继承,使用implements关键字让对象的类实现这个接口。
在UML图中,接口名称和方法名称使用斜体。虚线和空心三角形用于指向接口。
接口中所有的数据域都是public static final,所有的方法都是public abstract,所以Java允许忽略这些修饰符。
//一个几何接口 interface GeometricInterface { double getArea(); double getPerimeter(); } //一个几何对象 public abstract class GeometricObject { private String color = "white"; private boolean filled; private java.util.Date dateCreated; /** Construct a default geometric object */ protected GeometricObject() { dateCreated = new java.util.Date(); } /** Construct a geometric object with color and filled value */ protected GeometricObject(String color, boolean filled) { dateCreated = new java.util.Date(); this.color = color; this.filled = filled; } /** Return color */ public String getColor() { return color; } /** Set a new color */ public void setColor(String color) { this.color = color; } /** Return filled. Since filled is boolean, * the get method is named isFilled */ public boolean isFilled() { return filled; } /** Set a new filled */ public void setFilled(boolean filled) { this.filled = filled; } /** Get dateCreated */ public java.util.Date getDateCreated() { return dateCreated; } @Override public String toString() { return "created on " + dateCreated + "\ncolor: " + color + " and filled: " + filled; } } //一个矩形类,继承GeometricObject 类,实现GeometricInterface 接口 public class Rectangle extends GeometricObject implements GeometricInterface { private double width; private double height; public Rectangle() { } public Rectangle(double width, double height) { this.width = width; this.height = height; } /** Return width */ public double getWidth() { return width; } /** Set a new width */ public void setWidth(double width) { this.width = width; } /** Return height */ public double getHeight() { return height; } /** Set a new height */ public void setHeight(double height) { this.height = height; } @Override /** Return area */ public double getArea() { return width * height; } @Override /** Return perimeter */ public double getPerimeter() { return 2 * (width + height); } } //一个圆类,继承GeometricObject 类,实现GeometricInterface 接口 public class Circle extends GeometricObject implements GeometricInterface { private double radius; public Circle() { } public Circle(double radius) { this.radius = radius; } /** Return radius */ public double getRadius() { return radius; } /** Set a new radius */ public void setRadius(double radius) { this.radius = radius; } @Override /** Return area */ public double getArea() { return radius * radius * Math.PI; } /** Return diameter */ public double getDiameter() { return 2 * radius; } @Override /** Return perimeter */ public double getPerimeter() { return 2 * radius * Math.PI; } /* Print the circle info */ public void printCircle() { System.out.println("The circle is created " + getDateCreated() + " and the radius is " + radius); } }
View Code