As showed in Lesson 2 ,extending classes can be a powerful tool. However,there may be times you want to create a class that must be extended to use it .Abstract classes are just this. In declaring a class to e abstract ,you can also declare functions,where you give the name and what parameters they take;however,leave the implementation up to classes that will extend this one.
In doing this,you can define a template of how the child class must look. The child must implement all of the abstract class's abstract methods to extend it .In Short, Abstract classes allow you to define a common base for several concrete classes.
A simple example :
abstract class Animal { abstract protected function eat();
abstract protected function sleep();
public function die() {
// Do something to indicate dying
}
}
we define
eat()and sleep()as abstract because different types of animals (e.g. lion, bear, etc.) that will inherit from Animaleat and sleep in different ways. But all animals die the same way. So we can define a common function for that. Using an abstract class helped us:1.) declare some common methods that all
Animals should have, and 2.) define common behavior for
Animals. So, when you extend Animal, you won't have to rewrite the code for die()
No comments:
Post a Comment