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
.