Multiple inheritance design issue in Java

前端 未结 7 1327
醉梦人生
醉梦人生 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:41

    Looking at it, my first feeling is that your model is a bit complicated.

    A word has a String to describe the word itself being stored in the Word object along with a class to say it's a noun, verb, adjective, etc. Another property of a Word is the length of the string stored in the Word object.

    Think of things in terms of "is-a" and "has-a" relationships and you can remove a lot of complexity.

    For instance why do you need a WordDescriptor that extends AbstractWord? Is a word going to change from a verb to an adjective? I would have thought that the word type was set when the object was created and would not change during the lifetime of the Word object. Once you had a Word object for the word "Australia" the Kind of word would not change for the lifetime of the object.

    Hmmm. Maybe you might have a Word object representing the word "bark" after instantiating the object with a type of "verb" to describe the sound a dog makes. Then you realise that you actually needed to have the Word object to represent a noun that describes the covering of a tree. Possible, but both the dog's bark and the tree's bark can exist.

    So I think the model you've chosen is a bit too complicated and that your question can be resolved by going back and simplifying your original object model.

    Start by asking yourself a question for each of the inheritance aspects of your basic model.

    When I say Class B extends Class A, can I say that Class B "is-a" Class A and that I am specialising its behaviour?

    For example, a base class Animal can be extended to provide the specialised class of Kangaroo. Then you can say that "the kangaroo "is-a" Animal. You are specialising the behaviour.

    Then look at the attributes, a Kangaroo has a Location attribute to describe where it is found. Then you can say a Kangaroo "has-a" location. A Kangaroo "is-a" location doesn't make sense.

    Similarly, a Word "has-a" length. And the statement a Word "is-a" length just doesn't make sense.

    BTW All Australian references in this post are deliberate to celebrate Australia Day which is today 26th January!

    HTH

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