Any way to extend two or more classes in java?

前端 未结 12 1454
再見小時候
再見小時候 2021-01-17 02:20

I know that Java does not allow us to extend more than one class. I know that interfaces also exist and I don\'t want to use them this time. Is there some kind of trick or w

相关标签:
12条回答
  • 2021-01-17 02:59

    NO.

    go for interfaces.No multiple inheritance in Java.

    Multiple inheritance can cause the diamond problem.

    JAVA omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than benefit. This primarily consists of operator overloading (although it does have method overloading), multiple inheritance, and extensive automatic coercions _ Dr. James Gosling

    0 讨论(0)
  • 2021-01-17 02:59

    Multiple inheritance adds complexity with little benefits, that's why it is not present in java Why is Multiple Inheritance not allowed in Java or C#?

    One way I can think of is to write your program needing multiple inheritance in a language that supports it e.g.C++ and then make your Java code interact with the output from that program e.g using files or databases.

    0 讨论(0)
  • 2021-01-17 03:05

    Multiple inheritance in java is usually done by implementing multiple interfaces. You can not extend more than one class. A possible workaround may be to use some kind of object composition for instance aggregation.

    0 讨论(0)
  • 2021-01-17 03:05

    To avoid diamond problem Java does not support Multiple Inheritance through classes but it supports using interfaces. So you may use Association Relationship. e.g.

    Class A {}
    Class B {}
    Class C implements SomeInterface {
      A a;
      B b;
      // setter getter for a and b and other methods
    }
    
    0 讨论(0)
  • 2021-01-17 03:09

    Java not support this for classes.You can use multiple interfaces.You can find what the problem with multiple inheritance in java

    You can use inner classes like

     public class class1 extends class2{
      class Inner extends class3{
    
        }
       }
    

    SEE HERE

    0 讨论(0)
  • 2021-01-17 03:09

    Answer is No. But you can do this if helps:

    A extends B
    B extends C

    so A extends B and C

    0 讨论(0)
提交回复
热议问题