Object-Oriented Programming for Smartypants - DART EDITION. Part I ~Inheritance~
Everything in Dart is an object. Know this and know peace...
What are Objects and what is Object Oriented Programming(OOP)?
OOP is a form of Programming that relies on the concepts of Objects and Classes. These Objects can have both attributes(or properties) and behaviors(or methods).
There are four pillars or principles of OOP they are Inheritance, Abstraction, Encapsulation, and Polymorphism.
The benefit of objects is that they often closely correspond to things in the real world. For example, a bookstore's program might have objects like "book", "genre", "author" and "customers". So a book can have a property called 'name' and a method called 'displayTheReviews'.
Classes on the other hand are blueprints or templates from which we create our objects. These also possess properties and methods. A class is usually a generic category such as "Animal". Animals have general features such as:
they have limbs
they eat.
A dog is a type of animal and so is a cat, both can conveniently inherit from the animal class.
This leads us to our first pillar of Object Orient Programming:
Inheritance.
Inheritance is simply the idea of having a hierarchy of classes in which a child class derives (inherits) features of their parents like in the case of the Animal class example.
In order to use Inheritance, we use the 'extends' keyword after declaring the child class.
class Animal{
int limbs=4;
void eat(){print('eats food');}
}
class Dog extends Animal{
}
Voila! All the properties and methods of our Animal class also belong to our Dog class now.
To show that Dog has successfully inherited the properties of Animal, we first create an object of Dog class like so...
Dog Mandy = Dog();
...and then access it's properties using dot notation
void main(){
Dog Mandy = Dog();
print('Mandy has ${Mandy.limbs} limbs');
}
class Animal{
int limbs=4;
void eat(){print('eats food');}
}
class Dog extends Animal{
}
This will be printed to the console.
Mandy has 4 limbs
.
Great!
We were able to use the properties of Animal without explicitly declaring it in our Dog class, this is useful because it prevents us from repeating code unnecessarily. So if we have another class like Cat, all we have to do is extend Animal class and we're good to go.
Finally, aside from its parents' properties, a child class can have its own unique properties
class Dog extends Animal{
String favoriteGame ='fetch';
}
Nice! So this, in a nutshell, is Inheritance in OOP.
Watch out for PART II where we discuss Abstraction !!!!!