关于接口的定义,它根本没有提供任何具体实现,它允许创建者确定方法名,参数列表和返回类型,但是没有任何方法体。接口只提供了形式,而未提供任何具体实现。
接口 interface 关键字,可以在前面添加public关键字(仅限于该接口在于其同名文件中被定义),如果不添加public关键字,则它只具有包访问权限,这样它就只能在同一个包内可用。
接口也可以包含域,但是这些域都是隐式的是 static 和 final 。
接口中可以显式的将方法声明为public的,即使你不这么做,它们也是public的。
看一下完整的代码:
interface Rodents{ int value = 10; void play(int n); void eat(); } class Mouses implements Rodents { @Override public void play(int n) { // TODO Auto-generated method stub System.out.println(this + "PLAT()" + n); } @Override public void eat() { // TODO Auto-generated method stub System.out.println(this + "EAT()"); } } class Gerbils implements Rodents { @Override public void play(int n) { // TODO Auto-generated method stub System.out.println(this + "PLAY()" + n); } @Override public void eat() { // TODO Auto-generated method stub System.out.println(this + "EAT()"); } } class SmallRed extends Mouses { public void play() { System.out.println(this + "PLAY()"); } public void play(int n) { System.out.println(this + "PLAY(INT)"); } public void eat() { System.out.println(this + "EAT()"); } } class BigBlack extends Gerbils { public void play() { System.out.println(this + "PLAY()"); } public void play(int n) { System.out.println(this + "PLAY(INT)"); } public void eat() { System.out.println(this + "EAT()"); } } public class Demo03 { static void tune(Rodents r) { r.play(10); r.eat(); System.out.println("------------------"); } static void tuneAll(Rodents[] R) { for (Rodents r : R) { tune(r); } } public static void main(String[] args) { // TODO Auto-generated method stub Rodents[] rodents = { new Mouses(), new Gerbils(), new SmallRed(), new BigBlack() }; tuneAll(rodents); } }