Once a Java class implements a Java interface we can use an instance of that class as an instance of that interface like this.
public interface MyInterface {
public String hello = "Hello";
public void sayHello();
}
public class MyClass implements MyInterface {
public void sayHello() {
System.out.println(MyInterface.hello);
}
public void extra(){
System.out.println("this is extra");
}
}
MyInterface myInterface_instance = new MyClass ();
myInterface_instance .sayHello();
But my question is what is the advantage of creating like this?. If we do this it will narrow down the extra methods and attributes in the class that are not in the interface as well. ex
we can't use myInterface_instance.extra()
So why are we instantiating java interfaces like this, rather than assigning it to its own class instance like this?
MyClass myclass_instance = new MyClass ();