Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When two classes implement the same interface [closed]

Tags:

java

interface

Suppose there are 2 classes which implement a same interface and the methods from that interface. If I call a method directly from the interface, what is what decides which implementation will be returned (from first or second class) ?

like image 713
Madrugada Avatar asked Nov 30 '22 04:11

Madrugada


2 Answers

package test;
    public interface InterfaceX {
    int doubleInt(int i);
}

package test;
public class ClassA implements InterfaceX{
    @Override
    public int doubleInt(int i) {
        return i+i;
    }
}

package test;
public class ClassB implements InterfaceX{
    @Override
    public int doubleInt(int i) {
        return 2*i;
    }
}

package test;
public class TestInterface {
    public static void main(String... args) {
        new TestInterface();
    }
    public TestInterface() {
        InterfaceX i1 = new ClassA();
        InterfaceX i2 = new ClassB();
        System.out.println("i1 is class "+i1.getClass().getName());
        System.out.println("i2 is class "+i2.getClass().getName());
    }
}
like image 55
Michael Besteck Avatar answered Dec 04 '22 15:12

Michael Besteck


You don't call a method directly from an interface, you call it on a reference that points to an instance of a class. Whichever class that is determines which method gets called.

like image 24
Bill the Lizard Avatar answered Dec 04 '22 14:12

Bill the Lizard