接口和类层次结构

问题描述 投票:0回答:1
  1. 接口 I1{ int f(int i);}
  2. 接口 I2{ int f(I i);}
  3. 接口 I 扩展 I1, I2{}
  4. 公共类 InterfaceExample 实现 I {
  5. A a = 新A();
  6. B b = 新 B();
  7. 我我;
  8. I1 i1;
  9. I2 i2;
  10. public static void main(String[] args) {
  11.    InterfaceExample example = new InterfaceExample();
    
  12.    System.out.println(example.b.f(10)); 
    
  13.    System.out.println(example.a.f(example.b));
    
  14.    System.out.println(example.a.f(example.a));
    
  15. }
  16. A 类实现 I {
  17.    int x = 95;
    
  18.    public int f(I i){ return f(x) + 22 ;}
    
  19.    public int f(int i) { return i + 8;}
    
  20. }
  21. B 类扩展 A 实现 I1 {
  22.    int y = 166;
    
  23.    public int f(I i){ return i.f(y);}
    
  24.    public int f(int i) { return f(a) - 8;}
    
  25. }

第 12、13、14 行给出了数字 166、125、125。我已经明白如何得到 125,但第一个数字让我感到困惑

java interface implements class-hierarchy
1个回答
0
投票

“...我已经明白如何得到 125,但第一个数字让我感到困惑”

对于第一个数字,

    调用
  • Bf(int)
  • 从这里开始,使用参数 a 调用 Bf(I)
  • 这会调用 af(int) 方法,参数为 y, 166,返回 y + 8
  • 最后,从f(a)的结果中减去8
B.f(a.f(166 + 8) - 8)
© www.soinside.com 2019 - 2024. All rights reserved.