Home Interface, abstract class and inhereting subclass with same Method, that gets different type arguments, wich is used?
Reply: 3

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

MrCrocodileCCX
1#
MrCrocodileCCX Published in 2017-12-07 22:15:45Z

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?

Gon
2#
Gon Reply to 2017-12-07 22:59:20Z

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();
Dragonthoughts
3#
Dragonthoughts Reply to 2017-12-07 22:19:10Z

The method with the closest match to your type arguments will be used. But for compatible numerical, the deepest declared one.

Rafal
4#
Rafal Reply to 2017-12-07 22:39:38Z

You can also see that the type of "al" object is an interface type, so you can`t call the method from super class without casting, you also can`t call any method from AbstractLight without casting. You can only call methods there were declared in interface class. In that case, compiler will favour the method from the interface class. You can force the compiler to call a method from abstract class if you write something like that:

System.out.println(((AbstractLight)al).change(100));
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.344687 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO