Say i have an interface I with method doIt();
Now i have a class C that implements I and hence provides the implementation for doIt();
For the following code in Class Hello
public class Hello{
I i = new I();
i.doIt();
}
1.) Now where does it take the implementation of doIt() from?
2.) What if there was another class HelloWorld implementing I too with a different iplementation for the doIt() function. Then which implementation would it have taken?
Try compiling this stuff. You can only instantiate a
Classwhich implements theInterfaceand not theInterfacedirectly.An
Interfaceis just like a contract which aClassagrees to when itimplementsit; and within the agreement of theInterface,Classprovides the implementation of it.