Inheritance is a fundamental concept in object-oriented programming that allows 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.
Polymorphism is the ability of 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.
Inheritance
- Base Class and Derived Class: A base class is a general class that defines common properties and methods. A derived class is a specialized class that inherits from a base class and adds its own properties and methods.
- Inheritance Hierarchy: Classes can form a hierarchical relationship, where a derived class can inherit from another derived class.
- Overriding Methods: A derived class can override methods defined in its base class to provide its own implementation.
Example:
Code snippet
class Animal {
var name: string
func makeSound() {
print("Generic animal sound")
}
}
class Dog: Animal {
func bark() {
print("Woof!")
}
}
Polymorphism
- Static Polymorphism: Occurs at compile time and is achieved through method overloading.
- Dynamic Polymorphism: Occurs at runtime and is achieved through method overriding.
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)
Key Points:
- Inheritance allows you to create a hierarchy of classes and reuse code.
- Polymorphism enables you to write more flexible and reusable code.
- Inheritance and polymorphism are fundamental concepts in object-oriented programming.
By understanding and applying inheritance and polymorphism, you can create well-structured, modular, and maintainable Carbon programs.