CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Dec 2010
    Posts
    907

    When should I use interfaces and other times subclasses?

    Say a parrot and an human are both a whistler
    and they also some animals

    but you would have
    Code:
    class Human extends Animal implements Whistler
    Animal - position 1
    Whistler - position 2
    How do you decide putting which entities at which positions?
    thanks
    Jack
    Last edited by lucky6969b; September 4th, 2012 at 03:24 AM.

  2. #2
    Join Date
    May 2009
    Posts
    2,413

    Re: When should I use interfaces and other times subclasses?

    Quote Originally Posted by lucky6969b View Post
    How do you decide putting which entities at which positions?
    It's Java right?

    It doesn't matter from a design standpoint. These are equally fine (assuming you have a choise of making both Animal and Whistler either class or interface):

    class Human extends Animal implements Whistler
    class Human implements Whistler extends Animal
    class Human extends Whistler implements Animal
    class Human implements Animal extends Whistler
    class Human implements Animal, Whistler
    class Human implements Whistler, Animal

    They all say the same: Human inherits Animal and Whistler. The difference is implementation convenience only. Class extension allows you to inherit implementation, interface implementation does not.

    If you think many/most subclasses will benefit from a shared inherited implementation then you can supply it in a superclass (which is then extended by all subclasses). BUT it's almost always better NOT to inherit implementation at all (because it leads to the brittle superclass problem). You can always work with interfaces only. It's more flexible. Class extension is never needed but may be convenient sometimes (for implementation purposes but never from a design standpoint).
    Last edited by nuzzle; September 4th, 2012 at 11:33 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured