Object-Oriented Programming (OOP) is a programming paradigm that models real-world entities as objects. Objects have properties (attributes) and behaviors (methods). In Carbon, OOP is a fundamental concept that allows you to create modular, reusable, and maintainable code.
Classes and Objects
A class is a blueprint for creating objects. It defines the properties and methods that objects of that class will have. An object is an instance of a class.
Example:
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."
}
}
var person1: Person = Person(name: "Alice", age: 30)
var person2: Person = Person(name: "Bob", age: 25)
Encapsulation
Encapsulation is the bundling of data (properties) and methods (behaviors) into a single unit (object). It helps protect the internal state of an object and prevents unauthorized access.
Inheritance
Inheritance is the ability of one class (derived class) to inherit properties and methods from another class (base class). This promotes code reuse and creates a hierarchical relationship between classes.
Example:
Code snippet
class Animal {
var name: string
func makeSound() {
print("Generic animal sound")
}
}
class Dog: Animal {
func bark() {
print("Woof!")
}
}
var dog: Dog = Dog(name: "Buddy")
dog.makeSound() // Output: "Woof!"
Polymorphism
Polymorphism allows objects of different classes to be treated as if they were of the same type. It enables you to write more flexible and reusable code.
Example:
Code snippet
func printAnimalSound(animal: Animal) {
animal.makeSound()
}
var dog: Dog = Dog(name: "Buddy")
var cat: Cat = Cat(name: "Whiskers")
printAnimalSound(dog)
printAnimalSound(cat)
OOP in Carbon
Carbon provides a robust set of features for object-oriented programming, including:
- Classes and objects
- Encapsulation
- Inheritance
- Polymorphism
- Interfaces
- Generics
By understanding and applying OOP principles in Carbon, you can create well-structured, modular, and maintainable code.