Multiple inheritance design issue in Java

前端 未结 7 1395
醉梦人生
醉梦人生 2020-12-09 13:03

How do you deal with having only single inheritance in java? Here is my specific problem:

I have three (simplified) classes:

public abstract class A         


        
7条回答
  •  执笔经年
    2020-12-09 13:38

    With your specific example you could use the decorator pattern in conjunction with interfaces to supplement your Word class with additional functionality; e.g.

    // *Optional* interface, useful if we wish to reference Words along with
    // other classes that support the concept of "length".
    public interface Length {
      int getLength();
    }
    
    // Decorator class that wraps another Word and provides additional
    // functionality.  Could add any additional fields here too.
    public class WordExt extends AbstractWord implements Length {
      private final Word word;
    
      public class(Word word) {
        this.word = word;
      }
    
      public int getLength() {
        return word.getKind().length();
      }
    }
    

    In addition it's worth noting that the lack of multiple inheritence in Java isn't really the issue here; it's more a case of reworking your design. In general it's considered bad practice to over-use inheritence as deep inheritence hierarchies are difficult to interpret / maintain.

提交回复
热议问题