接口
一、接口的定义与实现
1.接口定义
使用interface来定义一个接口。接口的定义与类的定义类似,也是分为接口的声明和接口体,其中接口体由常量定义和方法定义两部分组成。
定义接口的基本格式如下:
[修饰符] interface 接口名 [extends 父接口名列表] {
[public] [static] [final]常量;
[public] [abstract]方法;
}
public interface CalInterface {
final float PI = 3.14159f;
float getAtea(float r);
float getCircumference(float r);
}
2.接口实现
接口在定义后,就可以在类中实现接口。使用关键字implements。
public class Cire implements CalInterface {
public float getArea(float r) {
float area = PI*r*r;
return area;
}
public float getCircumference(float r) {
float circumference = 2*PI*r;
return circumference;
}
public static void main(String[] args) {
Cire c = new Cire();
float f = c.getArea(2.0f);
System.out.prinltn(Float,toString(f));
}
}
二、通过接口来引用类——接口多态
interface InterA {
void fun();
}
class B implements InterA {
public void fun() {
System.out.println("This is B");
}
}
class C implements InterA {
public void fun() {
System.out.println("This is C");
}
}
class Test {
public static void main(String[] args) {
InterA a;
a = new B();
a.fun();
a = new C();
a.fun();
}
}
输出结果为:
This is B
This is C
三、接口多继承
public interface Attack {
public abstract void attack();
}
public interface medic {
public abstract void medictest();
}
public class shoottingman implements Attack {
public void attack() {
System.out.println("步兵可以攻击");
}
}
public class medicman implements Attack,medic {
public void medictest() {
System.out.println("医务兵可以治疗他人");
}
public void attack() {
System.out.println("医务兵也可以射击");
}
}
public class demotest {
public static void main(String[] args) {
shoottingman test = new shoottingman();
test.attack();
medicman test2 = new medicman();
test2.medictest();
test2.attack();
}
}
运行结果为:
步兵可以攻击
医务兵可以治疗他人
医务兵也可以射击