代码之家  ›  专栏  ›  技术社区  ›  MrCrocodileCCX

接口、抽象类和继承子类具有相同的方法,它们获取不同的类型参数,使用哪种方法?

  •  0
  • MrCrocodileCCX  · 技术社区  · 8 年前

    我有以下接口和类:

    public interface AlternateLight {
    
         public String change(long time);
    }
    
    public abstract class AbstractLight {
    
        public String change(int time) {
            return "AbstractLight Method was used";
        }
    }
    
    public class DistinctAlternateLight extends AbstractLight implements AlternateLight {
    
        public String change(long time) {
            return "DistinctAlternateLight Method was used";
        }
    }
    

    现在,我使用以下主方法调用方法change():

    public class WhatUsedTest {
    
        public static void main(String[] args) {
            AlternateLight al = new DistinctAlternateLight();
            System.out.println(al.change(100));
        }
    }
    

    它打印“使用了DistinctAlternateLight方法”,但为什么?我想因为我没有在100后面加一个“L”作为参数,它会调用抽象类的方法,因为它的方法需要整数。由于遗漏了“L”,我猜想编译器不会将100作为长值处理,并调用需要长时间的方法,但它确实如此。为什么会这样?

    3 回复  |  直到 5 年前
        1
  •  0
  •   Gon Arnav Borborah    8 年前

    这是由于多态性,如果您使用AlternateLight类声明变量,而此类型只能更改(很长时间)。

    小心。如果使用接口作为引用类型,并将实现类的对象分配给它,则只能调用在接口内声明的方法。这是很明显的,因为实现类可以定义自己的方法,这些方法不是接口和类之间契约的一部分。因此,要调用这些方法,必须使用类作为引用类型,如下所示:

    DistinctAlternateLight al =new DistinctAlternateLight();
    
        2
  •  0
  •   Dragonthoughts    8 年前

    将使用与类型参数最匹配的方法。 但对于兼容的数字,最深的声明之一。

        3
  •  0
  •   Rafal    8 年前

    您还可以看到,“al”对象的类型是一种接口类型,因此您不能在不进行强制转换的情况下从超类调用该方法,也不能在不进行强制转换的情况下从AbstractLight调用任何方法。您只能调用接口类中声明的方法。在这种情况下,编译器将支持接口类中的方法。 如果编写类似以下内容,则可以强制编译器从抽象类调用方法:

    System.out.println(((AbstractLight)al).change(100));