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

解决方案 »

  1.   

    接口就是为了让上层不需要知道底层的实现比如我现在需要工厂生产CPU,那么就有
    public interface Factory
    {
        public CPU produce();
    }public interface CPU
    {
        public void caculate();
    }
    而具体是哪个工厂生产的,是Intel还是AMD都无所谓,只要生产出来的是CPU就行了,而Intel可能生产出来的是P4,也可能生产出来的是P3,AMD生产出来的是Athlon还是Duron都没关系
    public class IntelFacotroy implements Factory
    {
        public CPU produce()
        {
              if(money > 2000)
                  return new P4CPU();
              else
                  return new P3CPU();
        }
    }public class AMDFacotroy implements Factory
    {
        public CPU produce()
        {
              if(money > 1500)
                  return new AthlonCPU();
              else
                  return new DuronCPU();
        }
    }public class P4CPU implements CPU
    {
    ……
      

  2.   

    Interface doesn't need an abstract method. If it has, an class drived from it has to realize it. It looks like a rule or a contract...
      

  3.   

    LS说得都对,不过这么说最明白:有了接口实现,就可以在其他地方这么干:
    interface Interface1; //声明一个接口引用
    Interface1 = new ClassItf(); //接口对接可以在其他地方切换接口:
    Interface1 = new MyClassItf(); //(假设MyClassItf也实现了接口Interface1)在其他地方就可以:
    Interface1.接口中的方法(); //不必关心是哪个类中的方法被调用了意思就是有了接口,可以不管那个类具体是什么类。如果没有接口,想调用接口中的方法就必须知道那个类是什么。