📄 interfacedefinedemo.java
字号:
//【例4-18】 接口的定义与主要特性。
//程序清单4-18: InterfaceDefineDemo.java
package e4_18;
public class InterfaceDefineDemo {
public static void main(String args[]) {
IA objIA;// 声明接口IA的引用变量objIA
IB objIB;// 声明接口IB的引用变量objIB
IShape objIShape;// 声明接口IShape的引用变量objIShape
Circle circle = new Circle(3);// 实例化一个圆
circle.show();
objIA = circle;// 使用接口引用变量来调用方法
System.out.println("objIA.getArea()=" + objIA.getArea());
Cylinder cylinder = new Cylinder(3, 2);// 实例化一个圆柱体
cylinder.show();
objIB = cylinder;// 使用接口引用变量来调用方法
System.out.println("objIB.getGirth()=" + objIB.getGirth());
objIShape = cylinder;// 使用接口引用变量来调用方法
System.out.println("objIShape.getVolume()=" + objIShape.getVolume());
}
}
interface IA {// 接口IA
public static final double PI = 3.145926;// PI常量
// 接口中的方法必须是抽象方法
public abstract double getArea();// 求面积
// 接口中不能定义构造方法
// public IA();
}
interface IB {// 接口IB
// 接口中的方法默认为public abstract类型的方法
double getGirth();// 求周长
}
// 接口的继承性:接口IShaple继承接口IA、IB
interface IShape extends IA, IB {
double getVolume();
}// 求体积
abstract class OutPut {// 含有抽象方法的类必定为抽象类
abstract void show();// 抽象方法必须用abstract修饰
}
// 若接口中的抽象方法没有被全部实现,则此类必须是抽象类,一个类可以实现多个接口
abstract class AbstractCircle extends OutPut implements IA, IB {
void show() {
}// 实现抽象类OutPut中抽象方法show()
public double getArea() {
return 0.0;
}// 实现接口IA中的抽象方法getArea()
// 接口IB中的抽象方法getGirth()没有被实现
}
class Circle extends AbstractCircle {// 圆类Circle
private double radius;// 新增属性:半径
public Circle(double radius) {
this.radius = radius;
}// 构造方法
public double getArea() {
return PI * radius * radius;
} // 方法覆盖
// 实现接口中的默认方法必定为public方法
public double getGirth() {
return 2 * PI * radius;
}
void show() {// 方法覆盖
System.out.println("圆的半径 = " + radius);
System.out.println("圆的面积 = " + getArea());
System.out.println("圆的周长 = " + getGirth());
}
}
// 圆柱体类Cylinder实现了抽象类和接口的所有抽象方法
class Cylinder extends OutPut implements IShape {
private double radius;// 新增属性:半径
private double high;// 新增属性:高
public Cylinder(double radius, double high) {// 构造方法
this.radius = radius;
this.high = high;
}
// 实现继承自接口IA中的抽象方法getArea()
public double getArea() {
return 2 * PI * radius * (radius + high);
}
// 实现继承自接口IB中的抽象方法getGirth()
public double getGirth() {
return (2 * PI * radius);
}
// 实现接口IShape中新增的抽象方法getVolume()
public double getVolume() {
return (PI * radius * radius * high);
}
void show() {// 实现抽象类OutPut中抽象方法show()
System.out.println("圆柱体的半径 = " + radius);
System.out.println("圆柱体的高度 = " + high);
System.out.println("圆柱体全面积 = " + getArea());
System.out.println("圆柱体腰围长 = " + getGirth());
System.out.println("圆柱体的体积 = " + getVolume());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -