Course program← Объектно ориентированное программирование
1История ООП
2Объект и Класс
3Базовые концепции ООП
4Принцип проектирования GRASP
5Принцип проектирования SOLID
6Паттерны GOF

The class as a description of a type

This lesson was translated automatically – it may contain errors.

Above – a blueprint of a car with dimensions, below – three cars of the same shape in different colours, built from that blueprint

Object-oriented programming (OOP) is a popular style of writing code that lets you structure a program as a set of interacting objects. The two key notions in OOP are the class and the object. They are often confused, but the difference between them is fundamental.

What is a class?

Picture the blueprint of a car. The blueprint states:

  • What body the car has and how many doors are in it
  • What engine sits under the bonnet
  • Which parts it is assembled from at the factory

A class is exactly that kind of “blueprint” or “template” for creating objects. It describes:

  • Attributes (data, fields): the characteristics the future object will have (for the Car class the attributes could be color, model, max_speed).
  • Methods (functions): the actions the object will be able to perform (for the Car class the methods could be start_engine(), drive(), brake()).

A class by itself takes up no space in the computer’s memory. It is just a description.

The description of the type does sit in memory, strictly speaking – but one copy for the whole program, no matter how many objects are created. Like a sheet of paper next to the car.

An example of a class

namespace Lecture1;

public class Car
{
    // Constructor – a special method that initialises a new object
    public Car(string color, string model)
    {
        Color = color;
        Model = model;
        IsEngineOn = false;
    }

    public string Color { get; set; }
    public string Model { get; set; }
    public bool IsEngineOn { get; set; }

    // Defining the methods (the behaviour of the class)
    public void StartEngine()
    {
        IsEngineOn = true;
        Console.WriteLine("Engine started!");
    }

    public void Drive()
    {
        if (IsEngineOn)
        {
            Console.WriteLine($"{Model} is on its way!");
        }
        else
        {
            Console.WriteLine("Start the engine first!");
        }
    }
}
#include <iostream>
#include <string>

class Car {
public:
    // Constructor – a special method that initialises a new object
    Car(std::string color, std::string model)
        : color_(std::move(color)), model_(std::move(model)) {}

    // Defining the methods (the behaviour of the class)
    void StartEngine() {
        is_engine_on_ = true;
        std::cout << "Engine started!" << std::endl;
    }

    void Drive() const {
        if (is_engine_on_) {
            std::cout << model_ << " is on its way!" << std::endl;
        } else {
            std::cout << "Start the engine first!" << std::endl;
        }
    }

    const std::string& color() const { return color_; }
    const std::string& model() const { return model_; }

private:
    // Fields of the class: inside a class everything is private by default
    std::string color_;
    std::string model_;
    bool is_engine_on_ = false;
};
// Go has no classes: a type description is a struct plus methods on it.
type Car struct {
	Color      string
	Model      string
	IsEngineOn bool
}

// There is no separate constructor construct either.
// By convention people write a New… function – it plays that role.
func NewCar(color, model string) *Car {
	return &Car{Color: color, Model: model}
}

func (c *Car) StartEngine() {
	c.IsEngineOn = true
	fmt.Println("Engine started!")
}

func (c *Car) Drive() {
	if c.IsEngineOn {
		fmt.Printf("%s is on its way!\n", c.Model)
	} else {
		fmt.Println("Start the engine first!")
	}
}
class Car:
    # Constructor – a special method that initialises a new object
    def __init__(self, color, model):
        # Defining the attributes (the data of the class)
        self.color = color
        self.model = model
        self.is_engine_on = False

    # Defining the methods (the behaviour of the class)
    def start_engine(self):
        self.is_engine_on = True
        print("Engine started!")

    def drive(self):
        if self.is_engine_on:
            print(f"{self.model} is on its way!")
        else:
            print("Start the engine first!")
class Car {
    isEngineOn = false;

    // Parameters marked public become fields of the object right away
    constructor(
        public color: string,
        public model: string,
    ) {}

    startEngine(): void {
        this.isEngineOn = true;
        console.log("Engine started!");
    }

    drive(): void {
        if (this.isEngineOn) {
            console.log(`${this.model} is on its way!`);
        } else {
            console.log("Start the engine first!");
        }
    }
}
public class Car {
    private final String color;
    private final String model;
    private boolean isEngineOn;

    // Constructor – a special method that initialises a new object
    public Car(String color, String model) {
        this.color = color;
        this.model = model;
        this.isEngineOn = false;
    }

    public String getColor() {
        return color;
    }

    public String getModel() {
        return model;
    }

    public void startEngine() {
        isEngineOn = true;
        System.out.println("Engine started!");
    }

    public void drive() {
        if (isEngineOn) {
            System.out.println(model + " is on its way!");
        } else {
            System.out.println("Start the engine first!");
        }
    }
}
// Properties are declared right in the class header – that is the constructor.
class Car(val color: String, val model: String) {
    var isEngineOn = false
        private set

    fun startEngine() {
        isEngineOn = true
        println("Engine started!")
    }

    fun drive() {
        if (isEngineOn) {
            println("$model is on its way!")
        } else {
            println("Start the engine first!")
        }
    }
}