contactmatt
contactmatt

Reputation: 18630

Design Patterns: What is a type

A very basic question, but after reading the "Design Patterns: Elements of reusable OO Software" book, I'm a little confused.

The book states,

"An object's type only refers to its interface-the set of request to which it can respond. An object can have many types, and objects of different classes can have the same type."

Could someone please better explain what a Type is? I also don't understand how one object can have multiple types...unless the book is speaking of polymorphism....

Upvotes: 3

Views: 138

Answers (3)

k3b
k3b

Reputation: 14775

May be an example helps to clarify. I Assume that class is a special kind of type.

  class Dog : Animal {...};
  class Fish : Animal {...};
  Dog lassie = new Dog();  
        // An object can have many types: 
        // lassie is a dog and an Animal

  Fish nemo = new Fish();  
    // objects of different classes can have the same type: 
    // lassie and nemo are animals

Upvotes: 1

David Conde
David Conde

Reputation: 4637

Think of types as contracts. Suppose you have a Zoo park, and you have an amount of animals in it.

Well, for any animal you have you can ensure that they have an assigned cage(an example). If the animals are mammals, you can get the specifics of the mammals. If they are swimmers you can get the temperature of the water they preffer and so on.

In this case, you would have a lot of types IEntity, IMammal and ISwimmer and a given object, for instance a penguin is of type IEntity and type ISwimmer. Keep in mind the analogy of type-contract and that's why the type states the requests to which a given object can reply, just like a contract says what can you do and what you can't do for a specific contracted task.

Hope my answer helps

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 882586

Types in this sense is not necessarily the objects actual type.

It's talking about types in the sense of what services the object provides. This may be multiple types with multiple inheritance, or a actual type with multiple interfaces.

For example, under Java, you may have an application class (with its actual type) which also provides a distinct user-input interface (keyboard and mice I/O).

That's an example of an object having multiple types.

An example of multiple objects with the same "type" (in the sense of your quote) is your classic geometric shape classes like square, rectangle, circle and so forth. All those distinct objects may have the same "type" since their interface consists of setPosition(), setSize() and drawShape().

Upvotes: 1

Related Questions