abstract class MyClass Implements Interface1, Interface2{ 
public void f(){} 
public vlid g(){} 

interface Interface1{ 
int VAL_A=1; 
int VAL_B=2; 
void f(); 
void g(); 

interface Interface2{ 
int VAL_B=3; 
inf VAL_C=4; 
void g(); 
void h(); 
}
Select the one right answer. 
(a) Interface1 and Interface2 do not match, therefore MyClass cannot implement them both. 
(b) MyClass only implements Interface1. Implementation for void h() from Interface2 is missing. 
(c) The declarations of void g() in the two interfaces clash. 
(d) The definitions of int VAL_B in the two interface class. 
(e) Nothing is wrong with the code, it will compile without errors
谁能给我解释下这道题。

解决方案 »

  1.   

    答案应该选e吧
    由于MyClass是abstract的,实现了Interface1, Interface2,不一定要为他们的方法提供具体的定义
      

  2.   


    选择d吧方法可以重名,因为它代表的是一种"定义"
         比如Interface1.g()完成业务A,Interface2.g()完成业务B
         那你就把实现了Interface1,Interface2的MyClass中的MyClass.g()定义成 既完成业务A又完成业务B
    至少不会出现矛盾
    但字段不可以重名,因为它代表了是一种"值"
    两个同名的字段 因为他们的"值"绝对会冲突的也许编译这个类的时候不会有问题,但编译MyClass.VAL_B肯定会出问题
      

  3.   

    abstract class MyClass implements Interface1, Interface2{  
    public void f(){System.out.println("abstract myclass: f()");}  
    public void g(){System.out.println("abstract myclass: g()");}  
    }  
    interface Interface1{  
    int VAL_A=1;  
    int VAL_B=2;  
    void f();  
    void g();  
    }  
    interface Interface2{  
    int VAL_B=3;  
    int VAL_C=4;  
    void g();  
    void h();  
    }
    class Bigclass extends MyClass implements Interface2{
    public void h(){System.out.println("Bigclass: h()");}
    }
    public class InterfaceTest{
    public static void main(String[] args){
    Bigclass class1 = new Bigclass();
    class1.f();
    class1.g();
    class1.h();
    System.out.println(class1.VAL_A);
    System.out.println(class1.VAL_B);//此处出错,因为系统找不具体哪个变量
    System.out.println(class1.VAL_C);
    }
    }
      

  4.   

    当然是e啦。a,b,c显然可以排除。至于d,虽然VAL_B同时存在于Interface1和Interface2中,但仍然是允许的,只不过要避免通过MyClass来引用VAL_B。所以,只要不出现MyClass.VAL_B就没问题,可以分别用Interface1.VAL_B和Interface2.VAL_B来使用不用接口中的常量。