0

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?

peroni_santo
  • 347
  • 1
  • 10
  • 2
    I don't understand the question. – Dave Newton Jun 09 '12 at 22:43
  • 1
    If class A is providing extra code to class B, then by very definition, B is a subtype of A. – Hassan Jun 09 '12 at 22:43
  • If B inherits from A how could it not be a sub-type of A, that's the definition of inheritance! Maybe B could get emancipated from A :-) – CD Smith Jun 09 '12 at 22:44
  • Are you asking if it is _okay_ to have B derive from A when B is not an A (fails [Liskov's substitution principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle))? -- Perhaps you're looking for [mixins](http://en.wikipedia.org/wiki/Mixin)? – sarnold Jun 09 '12 at 22:45
  • Yes, it does. Some languages such as C# and Ruby allow you to bolt on additional functionality without regard to inheritance. I believe what you are looking for is *duck typing.* – Robert Harvey Jun 09 '12 at 22:46

2 Answers2

0

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.

supercat
  • 69,493
  • 7
  • 143
  • 184
0

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.

Madara's Ghost
  • 158,961
  • 49
  • 244
  • 292