why can not a class not extend 2 classes in java

Generally, multiple inheritance is bad because of the Diamond Problem:

abstract class A {
 abstract void foo();
}

class B extends A {
 void foo () { return "bar"; }
}

class C extends A  {
 void foo() {return "baz"; }
}

class D extends B, C {
 void foo() { return super.foo(); } //What do I do? Which method should I call?
}

if we need 2 or more classes , Solutions:

  1. The first is aggregation: make a class that takes those two classes as fields.
  2. The second is to use interfaces.
  3. The third is to rethink your design.
  4.  make it extend from another class, and make that class extend from another again.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s