接口的概述

接口

一、接口的定义与实现

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();
	}
}

运行结果为:

步兵可以攻击
医务兵可以治疗他人
医务兵也可以射击
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值