Search code examples

Java interface type as constructor parameters

hi i am learning about Java interfaces. I read in Java tutorial that an interface is a reference type. Say I declare an interface

public interface INT {       public void dosomething();     }

and i have 3 classes, class A{}, B{} and C{}.

class A{} implements INT. 
class B{} extends A{} and implements INT. 
class C{} implement INT.

then i have another class D{} that has constructor

public class D{
  private INT a,b,c ;
  public D( INT a1, INT b1 , INT c1)  {
      a = a1; 
      b = b1;
      c = c1;

and then in main(), i instantiate a D object

D myobject = new D( new A(), new B(), new C() );

It is said that objects that are not related by class hierarchy can be used to interact with each other using interface. So in the above class, class C and A are not related and now the interface allows them to "talk" to each other? am i understanding this correct? what other advantages is there to declaring the constructor to be of interface type instead of the actual class type , as opposed to

private A a, B b, C c ;
public D( A a1, B b1 , C c1) {
   a=a1; b=b1;c=c1;

Is it something to do with polymorphism? sorry, this is my first attempt at OO, so am lacking some understanding here.


  • The huge advantage of using an interface type in a method (or constructor) parameter is that other programmers can call it and pass in their own classes that implement the interface. Classes that you didn't know about and which didn't even exist when you wrote the method/constructor. If you use concrete classes, callers have to use those classes, subclass them or change your code, all of which restrict them much more than implementing an interface.