Delegation Technique

Delegation Technique

What is delegation and how can I use it? Could you please give an example of a simple delegation technique?

Delegation is a technique where one object directly calls another object’s method in response to one of its own methods being called. The first object delegates to the second object the responsibility of processing the method call. Delegation is an alternative to inheritance when you want a class of objects to exhibit the behaviors of another. More accurately, delegation is a specific type of inheritance where a class inherits the behavior of another by delegating methods to the other class. You will sometimes use aggregation and delegation to simulate multiple inheritance in Java.

This is perhaps not the best example, but it demonstrates the technique. Let’s say that you want to create a label that’s also a frame. You might do this to create a simple pop-up message window. You can’t create a new class that subclasses both Label and Frame because Java doesn’t allow multiple inheritance of classes. Instead, you can subclass a Frame and give it a Label as a member variable, delegating to it the label behavior you want to inherit. The LabelFrame class shows how you might do this, delegating setText and setAlignment to the Label.

import java.awt.*;import java.awt.event.*;public class LabelFrame extends Frame {  Label _label;  public LabelFrame() {    _label = new Label();    add(_label, BorderLayout.CENTER);  }  void setText(String text) {    _label.setText(text);  }  void setAlignment(int alignment) {    _label.setAlignment(alignment);  }    public static final void main(String[] args) {    LabelFrame frame;    frame = new LabelFrame();    frame.addWindowListener(new WindowAdapter() {        public void windowClosing(WindowEvent e) {          Window window = e.getWindow();          window.setVisible(false);          window.dispose();          System.exit(0);        }      });       frame.setText("Publius Enigma");    frame.setAlignment(Label.CENTER);    frame.pack();    frame.setVisible(true);  }}


Share the Post: