Classes

Classes are the fundamental building blocks of object-oriented programming in Carbon. They serve as blueprints for creating objects, which represent real-world entities or concepts. A class encapsulates data (properties) and behavior (methods) into a single unit.

Defining Classes

To define a class in Carbon, you use the class keyword followed by the class name and a list of properties and methods.

Code snippet

class Person {
  var name: string
  var age: int

  func greet() -> string {
    return "Hello, my name is \(name) and I am \(age) years old."
  }
}

Properties

Properties are variables that define the characteristics of an object. They can be stored as instance variables or class variables.

  • Instance variables: Each object has its own copy of instance variables.
  • Class variables: Class variables are shared by all instances of the class.

Methods

Methods are functions that define the behavior of an object. They can access and modify the object’s properties.

Creating Objects

To create an object from a class, you use the class name followed by parentheses and provide values for the required properties.

Code snippet

var person1: Person = Person(name: "Alice", age: 30)

Accessing Properties and Methods

You can access an object’s properties and methods using the dot notation.

Code snippet

print(person1.name)
print(person1.greet())

Initializers

Initializers are special methods that are called when an object is created. They are used to initialize the object’s properties.

Code snippet

class Person {
  var name: string
  var age: int

  init(name: string, age: int) {
    self.name = name
    self.age = age
  }
}

Class Extensions

You can extend a class to add new properties and methods without modifying the original class definition.

Code snippet

extension Person {
  func walk() {
    print("Walking...")
  }
}

Classes are a powerful tool in Carbon for modeling real-world entities and creating well-structured, reusable, and maintainable code.

Introduction to Object-Oriented Programming (OOP)
Inheritance and Polymorphism

Get industry recognized certification – Contact us

keyboard_arrow_up