java中的接口

接口interface关键字比abstract的概念向前更迈进了一步。你可以将它看作是“纯粹的”抽象类。它允许类的创建者为一个类建立其形式:有方法名、参数列表和放回类型,但是没有任何方法体。 接口也可以包含有数据成员,但是他们隐含都是static和final的。接口只提供了形式,而未提供任何具体实现。

一个接口表示:“所有实现了该特定接口的类看起来都像它”。因此,任何类调用接口只需要知道该接口中有哪些方法。接口被用来建立类与类之间的“协议”。为了使用一个类遵循某个特定接口,需要使用implements关键字,它表示“该接口是这个类的外貌,但是我现在要声明他是如何运作的”。

接口使用的例子

class Note {
	private String noteName;

	private Note(String noteName) {
		this.noteName = noteName;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return noteName;
	}

	public static final Note MIDDLE_C = new Note("Middle c"),
			C_SHARP = new Note("C_Sharp"), B_FLAT = new Note("B Flat");

}

interface Instrument {
	// Compile-time constant:
	int VALUE = 5; // static & final

	// Cannot have method definitions:

	void play(Note n); // Automatically public

	void adjust();
}

class Wind implements Instrument {
	public void play(Note n) {
		System.out.println(this + ".play() " + n);
	}

	public String toString() {
		return "Wind";
	}

	public void adjust() {
		System.out.println(this + ".adjust()");
	}
}

class Percussion implements Instrument {
	public void play(Note n) {
		System.out.println(this + ".play() " + n);
	}

	public String toString() {
		return "Percussion";
	}

	public void adjust() {
		System.out.println(this + ".adjust()");
	}
}

class Stringed implements Instrument {
	public void play(Note n) {
		System.out.println(this + ".play() " + n);
	}

	public String toString() {
		return "Stringed";
	}

	public void adjust() {
		System.out.println(this + ".adjust()");
	}
}

class Brass extends Wind {
	public String toString() {
		return "Brass";
	}
}

class Woodwind extends Wind {
	public String toString() {
		return "Woodwind";
	}
}

public class Music5 {
	// Doesn’t care about type, so new types
	// added to the system still work right:
	static void tune(Instrument i) {
		// ...
		i.play(Note.MIDDLE_C);
	}

	static void tuneAll(Instrument[] e) {
		for (Instrument i : e)
			tune(i);
	}

	public static void main(String[] args) {
		// Upcasting during addition to the array:
		Instrument[] orchestra = { new Wind(), new Percussion(),
				new Stringed(), new Brass(), new Woodwind() };
		tuneAll(orchestra);
	}
}
无论你是要将其向上转型为一个被称为Instrument的常规类,或是一个被称为Instrument的抽象类,还是一个被称为Instrument的接口,都不是问题,它的行为都是相同的。事实上,你可以在tune()方法中看到, 没有任何证据来证明Instrument是一个常规类、一个抽象类,还是一个接口。

参考:Think in java 3.0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值