> For the complete documentation index, see [llms.txt](https://docs.ramsdenj.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.ramsdenj.com/introduction-4/introduction-2/composition-and-polymorphism.md).

# Composition and Polymorphism

## Composition

Composition means building complex behavior by combining simpler components, rather than inheriting from a base class.

“Has-a” relationship instead of “is-a.”

```python
class Engine:
    def start(self):
        print("Engine started")

class Car:
    def __init__(self):
        self.engine = Engine()  # Composition

    def start(self):
        self.engine.start()
        print("Car is ready to go!")
```

Car "has-a" engine, not "is-a"

Instead of inheriting from Engine, the Car contains it.

This decouples the classes and makes reuse easier.

## Polymorphism

Polymorphism allows you to use different objects interchangeably if they follow the same interface or behavior.

“Many forms” — the same interface can be implemented in multiple ways.

```python
class Shape:
    def draw(self):
        raise NotImplementedError()

class Circle(Shape):
    def draw(self):
        print("Drawing a circle")

class Square(Shape):
    def draw(self):
        print("Drawing a square")

def render(shape: Shape):
    shape.draw()

# Polymorphic use
render(Circle())  # Drawing a circle
render(Square())  # Drawing a square
```

`render()` doesn't care what kind of Shape it's drawing.

As long as the object implements `draw()`, it works.

This enables extensibility without modification - supports Open-Closed Principle.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.ramsdenj.com/introduction-4/introduction-2/composition-and-polymorphism.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
