Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Implementing multiple interfaces in java

In Java this is valid

 interface  Iface1{
    void func();
}

 interface  Iface2{
    void func();
}

class Demo implements Iface1, Iface2 {
    public void func(){

    }
}

but why is this not valid

interface Iface1 {
    void func(Integer a);
}

interface Iface2 {
    void func(Object a);
}

class Demo implements Iface1, Iface2 {
    public void func(Integer a) {
    }
}

In this case, since I implement Iface1, the contract of both Iface1 and Iface2 are fulfilled. Since Integer is a subclass of Object.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The compiler gives me error – Class ‘Demo’ must either be declared abstract or implement abstract method ‘func(Object)’ in ‘Iface2’

I was expecting this should work by only implementing the function with parameter Integer type

>Solution :

Iface2 declares func to accept any Object, so to implement that interface, a class must provide an implementation of func accepting any Object. For instance, the call demoInstance.func("this is a string") must be valid.

Demo‘s func only accepts Integers so it does not implement the interface.

In your first setup, the signature of both methods is the same in both interfaces, so there’s a valid implementation for either in Demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading