Inheritance, does the "is a" relationship always have to hold?

102 Views Asked by At

If class B inherits from class A, does class B always have to be a sub-type of A when used in inheritance?

I am thinking if it is possible to use inheritance to provide extra code to B, when B is not a subtype of A?

2

There are 2 best solutions below

0
On

If type A inherits from B, that means two things:

  1. Class `A` will be able to use public and protected static methods from class `B`, without having to specify the class name, and objects of class `A` will implicitly include all public and protected class members from `B` without having to respecify them.
  2. Any code accepting objects of type `B` will, at at compile time, accept objects of type `A`, and objects of class `A` will be able to use class `B`'s public and protected instance methods on themselves.

Interfaces essentially embody concept #2 but not #1 (since interfaces have no static methods, and have no members that can be used implicitly without having to specify them). There is no built-in way to achieve #1 without #2; the only significant benefit of having #1 without #2 would be to save typing.

0
On

If:

class B extends A

Than B is by definition a subtype of A.

If you don't want that, you can use PHP's traits, which is basically interfaces with implementation.