Inheritance
Monday, June 17, 2024 12:29 PM
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one
class (subclass or derived class) to inherit the properties and behaviors (methods and fields) of
another class (superclass or base class). This concept promotes code reuse and supports the
hierarchical organization of classes based on their similarities and differences.
1. Superclass and Subclass
- Superclass: Also known as a base class or parent class, it is the class from which
properties and behaviors are inherited.
- Subclass: Also known as a derived class or child class, it inherits properties and
behaviors from its superclass and can also define additional features or override existing
ones.
2. Syntax in Dart
- In Dart, a subclass can inherit from a superclass using the `extends` keyword.
class Animal {
String name;
void makeSound() {
print('Some generic sound');
}
}
class Dog extends Animal {
@override
void makeSound() {
print('Bark bark!');
}
}
Here, `Dog` is a subclass of `Animal`.
1. Code Reuse
- Inheritance promotes code reuse by allowing subclasses to inherit behaviors and
properties from their superclass. This reduces redundancy and makes code more modular.
2. Method Overriding
- Subclasses can provide a specific implementation of a method that is already defined in
its superclass. This is achieved using the `@override` annotation in Dart.
class Cat extends Animal {
@override
void makeSound() {
print('Meow!');
}
}
3. Access Modifiers
- Dart supports access modifiers (`public`, `private`, and `protected`) to control access
to superclass members in subclasses.
Dart(OOP) Page 1
class Animal {
String name;
int _age; // Private member, accessible only within this
class
void _privateMethod() {
print('Private method');
}
}
class Dog extends Animal {
void accessSuperclassMembers() {
name = 'Dog'; // Accessing public member from superclass
_age = 3; // Error: Private member cannot be accessed in
subclass
_privateMethod(); // Error: Private method cannot be
accessed in subclass
}
}
4. Constructor Inheritance
- Dart subclasses inherit constructors from their superclass. If the superclass doesn’t
have a default constructor, subclasses must explicitly call one of the constructors from the
superclass using the `super` keyword in their constructors.
class Animal {
String name;
Animal(this.name);
}
class Dog extends Animal {
String breed;
Dog(String name, this.breed) : super(name);
}
5. Single Inheritance
- Dart supports single inheritance, meaning a subclass can inherit from only one
superclass. This simplifies the class hierarchy but requires careful design to manage
complexity.
Types of Inheritance
- Single Inheritance: A subclass inherits from only one superclass.
- Multiple Inheritance is not supported in Dart. However, Dart allows for **Mixin**
classes to simulate some behavior of multiple inheritance.
Dart(OOP) Page 2