Interface, abstract class and inheriting subclass with same Method, that gets different type arguments, which is used?

I have these interface and classes:

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";
    }
}

Now I call the method change() with following main-method:

public class WhatUsedTest {

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

It prints “DistinctAlternateLight Method was used”, but why? I thought since I didn’t put a “L” behind the 100 as argument, it would call the method of the abstract class, because its method takes integers. With missing out on the “L”, I guessed the compiler wouldn’t handle the 100 as a long value and call the method taking longs, but it does. Why is that so?

Answer

It’s due to the polymorphism, if you declare your variable with AlternateLight class and this type has only acces to change(long time).

be careful. If you use interface as reference type and assign an object of implementing class to it then you can call only those methods that are declared inside the interface. This is quite obvious because the implementing class can define methods of its own that are not a part of the contract between the interface and class. So, to call those methods you have to use the class as reference type as following:

DistinctAlternateLight al =new DistinctAlternateLight();

Leave a Reply

Your email address will not be published. Required fields are marked *