Java: Implementing multiple inheritance of classes using inner classes

Source: Internet
Author: User
Tags abstract inheritance

Java does not support multiple inheritance of classes, but you can use an inner class to inherit the implementation of more classes.

In the following example, the target class needs to inherit two abstract classes (A and B). The target class C itself inherits Class A and inherits another class B using an anonymous inner class.

Multiimplementation.java

abstract class A {
  abstract void methodA();
}
abstract class B {
  abstract void methodB();
}
class C extends A {
  @Override
  void methodA() {
    System.out.println("extends A's method");
  }
  B getB() {
    return new B() {
      @Override
      void methodB() {
       System.out.println("extends B's method");
      }
    };
  }
}
public class MultiImplementation {
  public void doA(A a) {
    a.methodA();
  }
  public void doB(B b) {
    b.methodB();
  }
  public static void main(String[] args) {
    MultiImplementation mi = new MultiImplementation();
    C c = new C();
    mi.doA(c);
    mi.doB(c.getB());
  }
}

Results:

extends A's method
extends B's method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.