对于接口的解释,各种书中都是千篇一律--更合理的实现多重继承提供一个框架指明多个类需要实现的方法等。看了很久,从给出的例子和语言解释中怎么也看不出接口的意思,这个程序规则定义为接口有点勉强。接口应该是两个(或多个)模块之间的交接协议,通过接口接收到了什么东西。而java的接口中没东西,就像下面这个例子:interface Interface1{ 有方法名 }
interface Interface2{ 有方法名 }public class ClassItf implements Interface1,Interface2
{
实现以上两个接口中的方法
}
输出结果如果注释掉 /* implements Interface1,Interface2 */ ,也能输出同样的结果,那定义了接口有什么用呢?而且在另一个*.java程序中再用Interface1,实现的方法是另一种写法的情况吓,那就应该说是实现两个不同的方法用了同一个接口???两个程序用了同样的方法名而已。是这样吗????
interface Interface2{ 有方法名 }public class ClassItf implements Interface1,Interface2
{
实现以上两个接口中的方法
}
输出结果如果注释掉 /* implements Interface1,Interface2 */ ,也能输出同样的结果,那定义了接口有什么用呢?而且在另一个*.java程序中再用Interface1,实现的方法是另一种写法的情况吓,那就应该说是实现两个不同的方法用了同一个接口???两个程序用了同样的方法名而已。是这样吗????
interface Animal{
public void run();
}
class Dog implements Animal{
public void run(){
System.out.println("dog run");
}
}
class Cat implements Animal{
public void run(){
System.out.println("cat run");
}
}
public class Test{
public static test(Animal animal){
animal.run();
}
public static void main(String[] args){
Animal dog=new Dog();
Animal cat=new Cat();
test(dog);
test(cat);
}
}接口的作用是提供一个统一的接口,通过一个统一的接口调用,产生不同的行为。