Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java interface type as constructor parameters

Tags:

java

oop

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.

like image 218
ghostdog74 Avatar asked Sep 07 '25 05:09

ghostdog74


2 Answers

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.

like image 186
Michael Borgwardt Avatar answered Sep 11 '25 15:09

Michael Borgwardt


Your code is absolutely correct.

The advantage of using interface instead of real class is that you expose only the communication interface of the object and not the way the object is implemented. It allows you to change the implementation in any time without breaking the client code.

This thing is called encapsulation: hiding the implementation details from the outside of the class. It is always a good thing.

About communication: they can't communicate directly. But you can call method dosomething on any of the passed objects, because they all implement the same interface. So, somewhere inside object D you can write:

a1.dosomething(); // called the method of A
b1.dosomething(); // called the method of B
c1.dosomething(); // called the method of C
like image 43
Vladimir Ivanov Avatar answered Sep 11 '25 15:09

Vladimir Ivanov