0

As per my understanding, there can be both class inheritance and interface inheritance. And interface is one of the ways to provide encapsulation.

Q1: Then why "Inheritance will always have weak encapsulation"?

Q2: composition with interface is considered to be a good design tool. How and why?

Please provide example in Java code(if possible) for better understanding.

sumit
  • 133
  • 2
  • 10

1 Answers1

0

Inheritance will not always have weak encapsulation.

Quoting awesome JavaWorld article

In an inheritance relationship, superclasses are often said to be "fragile," because one little change to a superclass can ripple out and require changes in many other places in the application's code. To be more specific, what is actually fragile about a superclass is its interface. If the superclass is well-designed, with a clean separation of interface and implementation in the object-oriented style, any changes to the superclass's implementation shouldn't ripple at all. Changes to the superclass's interface, however, can ripple out and break any code that uses the superclass or any of its subclasses. What's more, a change in the superclass interface can break the code that defines any of its subclasses.

I definitely reading the article and browsing the website for various different articles. Some Googling might help as well :)

Small example to describe weak encapsulation:

  class Base {

    public void foo() {
      bar();
    }

    public void bar() {}
  }

  class Derived extends Base {
    @Override
    public void bar() {
      foo();
    }
  }

  public static void main(String[] args) {
    new Child().bar();
  }

It would seem like overridden bar would call foo which would call bar in base class but turns out, this is an infinite recursion.

It is a fairly strong tool if used properly. For example, if implementing interface, you need to implement all methods from base class in derived class. If you know that there are methods with default behaviour, use Inheritance which doesn't require implementing all methods but only those that you need to override.

sam
  • 2,033
  • 2
  • 10
  • 13
  • @sam2090- thanks for the answer. Although "If you know that there are methods with default behaviour, use Inheritance which doesn't require implementing all methods but only those that you need to override" was not clear to me. – sumit Oct 08 '15 at 05:51
  • @sumit Check [here](http://stackoverflow.com/questions/19146979/why-inheritence-is-strongly-coupled-where-as-composition-is-loosely-coupled-in-j). it will definitely help you – sam Oct 08 '15 at 11:20