OOP: When is it an object?

前端 未结 20 1365
悲哀的现实
悲哀的现实 2021-01-30 23:01

I\'m trying to understand object orientation. I understand it a little bit of course, but sometimes I\'m not 100% clear. How do you decide what should be turned into an object (

20条回答
  •  星月不相逢
    2021-01-30 23:35

    It is an object if you need to think about it as... an object.

    That is, if you need an abstraction.

    The "key hole" in your example can be described on different levels of abstraction and only the last one from the list you would probably call "an object":

    1) Could be a boolean property, if you just need to know that your door has it:


    class Door
    {
        bool HasKeyHole;
    }
    

    2) Could be a pair of coordinates, if you just want to draw your door and put a circle in place of the key hole


     class Door
     {
        Point KeyHoleCoordinates;
     }
    

    3) Could be a specially defined class KeyHole if you want to encapsulate logic and some properties of a key hole and work with them together, probably passing them around, or allowing interaction with a Key


    class KeyHole
    {
        Point Coordinates;
        bool OpensWithKey(Key key);
    }
    
    class Door
    {
        KeyHole Hole;
    }
    

提交回复
热议问题