从头认识java-7.2 接口

这一章节我们来讨论一下接口。

之前我们已经聊过抽象类,他已经进行了第一步的抽象,把某些方法抽象出来,然后在子类那里实现,但他不是完全抽象。

而接口,就是进一步抽象,它里面全是没有实现的方法,所以的方法都在实现类里面实现。

1.概念

接口:就像类与类之间的一种协议,只需要知道某个类实现的某个接口, 那么,他就可以通过调用接口里面的方法来指向这个类的实现。


2.特性

(1)使用interface标注

(2)完全抽象

(3)属性域必须是public final static(这个是编译器自动转换的)

(4)方法必须是public

(5)向上转型,为父类指向子类对象提供途径,同时也使得java拥有多态这个特性

(6)不可以实例化

(7)接口可以多重实现

interface Instrument {
	int id=0;
	void Play();
}


3.实例

package com.ray.ch07;

public class Test {
	public void tune(Instrument instrument) {
		instrument.Play();
	}

	public void tune(Instrument[] instruments) {
		for (int i = 0; i < instruments.length; i++) {
			tune(instruments[i]);
		}
	}

	public static void main(String[] args) {
		Test test = new Test();
		// Instrument instrument = new Instrument();//error
		Instrument wind = new Wind();
		Instrument bass = new Bass();
		Instrument[] instruments = { wind, bass };
		test.tune(instruments);
		System.out.println(Instrument.id);// id是static
	}
}

interface Instrument {
	// private int id=0;//error
	// private void Play();//error

	int id = 0;

	void Play();
}

class Wind implements Instrument {

	@Override
	public void Play() {
		// id=2;//The final field Instrument.id cannot be assigned
		System.out.println(id);
		System.out.println("wind play");
	}
}

class Bass implements Instrument {
	@Override
	public void Play() {
		System.out.println("bass play");
	}
}


输出:

0
wind play
bass play
0


从上面的代码可以看见:

1.接口是不可以new 的

2.子类必须实现接口的方法

3.通过向上转型,以Instrument为类型定义的wind和bass,也可以调用play方法,而且运行时自动识别应该绑定那个play方法

4.由于wind和bass必须重写play,因此play一定是public,因为wind和bass不是继承Instrument

5.我们通过打印Instrument里面的id,知道id一定是static,因为可以直接使用Instrument调用,而不需要new

6.通过在实现类wind里面修改id,就可以看到他的提示,提示id是final的。

7.接口的多重实现我们将在后面讲述。


总结:这一章节主要讨论了接口的概念、特性,以及举例来说明这些特性。


这一章节就到这里,谢谢。

-----------------------------------

目录



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值