日期:2014-05-20  浏览次数:20735 次

(难)两个接口中有同样方法,又要实现这两个接口怎么办
两个接口中有同样方法,又要实现这两个接口怎么办?下面有一段代码,怎样正确执行?

[code=Java][/code]
interface A {
  public void xx() {
  }
}

interface B {
  public int xx() {
  return 0;
  }
}

public class C implements A,B {
  public C() {
  }
  
  //这里如何写接口A,B方法的实现

  public static void main(String[] args) {
  C cc = new C();
  }
}

------解决方案--------------------
有人这么要求你的话把他拉出去枪毙一百次……
------解决方案--------------------
写个内部类 或者
合并两个方法的功能~
------解决方案--------------------
在实现中明式写出接口的名字,
Java code
interface A { 
  public void xx(); 
} 

interface B { 
  public int xx();
} 

public class C implements A,B { 
  public C() { 
  } 
  public void A.xx(){
    //
  }
  public int B.xx(){
    //
  }
   

  public static void main(String[] args) { 
    C cc = new C(); 
  } 
}

------解决方案--------------------
我觉得曲线实现:
1、用一个类来实现interface A中的xx()方法,第二个类实现interface B中的xx()方法,同时在第二个类中继承第一个类。
2、用一个类来实现interface A中的xx()方法,同时在这个类中声明一个匿名内部类,这个匿名内部类实现interface B中的xx()方法。
------解决方案--------------------
探讨
interface A {
public void xx();
}

interface B {
public void xx();
}

------解决方案--------------------
在C#当可以用命名空间来区别实现的是哪一个接口,但JAVA还没遇到这种情况
------解决方案--------------------
啥情况都有啊...
------解决方案--------------------
接口不会这样写的啊,如果遇到这种情况,可以用内部类来写
Java code

interface  A {
    public void xx();
}

interface B {
    public int xx();
}

public class C implements A {        //类C实现A接口
    private int a = 0;
    private int b = 1;
    
    public void xx() {               //A接口中的xx()方法
        System.out.println(a);
    }
    
    public int ShowB() {             
        CC cc1 = new CC();
        return cc1.xx();
    }
    
    class CC implements B {          //内部类CC实现B接口
        public int xx() {            //B接口的xx()方法
            return b;
        }
    }
    
    public static void main(String[] args) {
        C c1 = new C();

        c1.xx();                        //调用实现接口A中的xx()方法,输出a值
        
        System.out.println(c1.ShowB());//调用ShowB方法来调用在内部类中实现接口B的方法xx(),输出b值
        
    }
}

------解决方案--------------------
Java code

package com.llh.Test;

interface A { 
    public void xx();
} 

interface B { 
    public int xx();
}
class C implements A {
    class BB implements B {
        public int xx() {
            System.out.println("B.xx()");
            return 0;
        }
    }
    
    public B getB() {
        return new BB();
    }
    
    public void xx() {
        System.out.println("A.xx()");
    }
}
public class Test2 {
    public static void main(String[] args) {
        C c = new C();
        c.xx();
        //直接创建内部类对象
        C.BB b = c.new BB();
        b.xx();
        //通过方法获得内部类对象引用
        象