How is loose coupling achieved using interfaces in Java when an implementation class is mandatory and bound to interface contract?

前端 未结 4 1582
囚心锁ツ
囚心锁ツ 2020-12-16 18:51

How is loose coupling associated with interfaces when we are bound to create an implementation class regardless? The implementation class is forced to implement all those me

4条回答
  •  鱼传尺愫
    2020-12-16 19:33

    Might below explanation can answer this :

    Into class A we need to have Object of class B. If directly exposure of B into A is there means there is Tight coupling. ex: one can add more methods into B or anything. Which means Behavior of A can be changed based on more exposure of B. But if B class is implementing any Interface and we are passing that ref of Interface into A. means whatever changes in B class further user A class is not bother because we use ref of Interface for accessing B and got only required access. Ex : class A { public void add( B b){ // Implementation } } class B{

        }
                this is Tight coupling. Because user can make any changes to class B which are directly exposed to class A and this defines Tight Coupling(Greater the exposure of depending Object , more Tight Coupling).  To resolve this one refer :
        Interface L{
    
        }
        class B implements L{}
        class A{
            public void add(L  b){
                // Implementation
            }
        }
    
            Since we are passing the ref of Interface L, adding changes into Implementation of B will not make any difference to class A.
    

提交回复
热议问题