Results 1 to 2 of 2
  1. #1
    javaplus is offline Member
    Join Date
    Nov 2007
    Posts
    97
    Rep Power
    0

    Default Delegation vs inheritance

    Hi everyone,

    I am interested in knowing the difference between inheritance and delegation pattern. When to use what?

    Regards.

  2. #2
    Programmist is offline Member
    Join Date
    Nov 2007
    Posts
    7
    Rep Power
    0

    Default

    If you're interested in design patterns you can go here, or do a Google search.

    I don't really consider inheritance and delegation to be major design patterns though. They are more like basic OO concepts.

    Inheritance is used to create a hierarchical-type code structure that tries to keep as much "common" code near the top of the hierarchy, so it can be reused by lower levels of the hierarchy. So, in this approach, classes get more specialized as you move toward the bottom of the hierarchy. In small, static systems, inheritance can be ok. But large inheritance chains can also lead to hard-to-maintain code. Read up on design patterns that favor composition over inheritance for more info when to use inheritance and when not to.

    Delegation is simply passing a duty off to someone/something else. Here is a simple example:

    Java Code:
    public class Information
    {
      public String getTemperature()
      {
         return TempGetter.getTemperature();
      }
    
      public String getTime()
      {
         return TimeGetter.getTime();
      }
    }
    In this example, I've got imaginary classes TimeGetter and TempGetter that have static methods for retrieving time and temperature. Rather than finding my own way to obtain these data, I use existing classes. Said another way, I delegate these tasks to these classes without knowing/caring about the details of how it gets done.

Similar Threads

  1. Inheritance
    By mew in forum New To Java
    Replies: 1
    Last Post: 12-07-2007, 06:08 PM
  2. Using interfaces with Delegation
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-06-2007, 01:49 PM
  3. Using Delegation in Java
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-06-2007, 01:44 PM
  4. Multiple Inheritance
    By mew in forum New To Java
    Replies: 1
    Last Post: 12-01-2007, 10:04 PM
  5. Inheritance in GUI
    By Marty in forum SWT / JFace
    Replies: 2
    Last Post: 05-11-2007, 12:54 AM

Posting Permissions

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