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) ?
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());
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With