Skip to main content

delegates in java

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
2 replies [Last post]
imagero
Offline
Joined: 2003-11-18

Java does not have delegate keyword like c#.
We can of course use delegates:

interface A {
void do1();
void do2();
}

class B implements A {
void do1() { }
void do2() { }
}

class C implements A {
B delegate = new B();
void do1() { B.do1(); }
void do2() { B.do2(); }
}

This is ok as long interface has only a few methods and if we do it occasionaly.
It would be nice however if we had the possibility to plug delegate to our class.
Something like this:

class C implements A delegate B {
//do1() is redirected to delegate
//our own implementation of do2()
void do2() { }
}

Delegates could be used as replacement for missing in java multiple inheritance.

If you like this idea please vote for bug 7152559
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7152559

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
bwillcott
Offline
Joined: 2007-06-01

Isn't this covered by normal class inheritance?

interface A {
  void do1();
  void do2();
}

class B implements A {
  @Override
  void do1() { ... }

  @Override
  void do2() { ... }
}

class C extends B {
  @Override
  void do2() { ... }
}
imagero
Offline
Joined: 2003-11-18

Since java have only single inheritance - NO.

Look at swing classes. Nearly each of them defines method addXXXListener. This results in thousands lines of code!

It could be solved short and elegant just with only one implementation plugged in each class using just one line of code.