Java interface type as constructor parameters

Hi, I’m learning about Java interfaces. I read in a Java tutorial that an interface is a reference type. Let's 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 a 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 create a D object

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

They say that objects that are not connected by a class hierarchy can be used to interact with each other using an interface. Thus, in the above class, classes C and A are not connected, and now the interface allows them to "talk" to each other? do i get it right? what other advantages exist for declaring an interface type constructor 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;
}

- ? , OO, .

+3
5

( ) , , . , /. , , , , .

+6

.

, , . .

: . .

: . dosomething , . , - D :

a1.dosomething(); // called the method of A
b1.dosomething(); // called the method of B
c1.dosomething(); // called the method of C
+3

, " C A, , " " ", .

+1

, C A , "" ?

. , , . , , , , . , "" , , , . D A, B C , , , .

, . , . . - , . , .

+1

@Michael Borgwardt . , , , , . .

, , , D INT. A, B, C , , ( ) D.

+1
source

Source: https://habr.com/ru/post/1782738/


All Articles