Abstract Class
An abstract class is a class with or without data members that provides some functionality and leaves the remaining functionality for its child class to implement. The child class must provide the functionality not provided by the abstract class or else the child class also becomes abstract.
Objects of an abstract and interface class cannot be created i.e. only objects of concrete class can be created.
To define a class as Abstract, the keyword abstract is to be used e.g. abstract class ClassName { }
Eg :
abstract class Furniture {
private $height, width, length;
public function setData($h, $w, $l) {
$this->height = $h;
$this->width = $w;
$this->length = $l;
}
//this function is declared as abstract and hence the function
//body will have to be provided in the child class
public abstract function getPrice();
}
class BookShelf extends Furniture {
private $price;
public setData($h, $w, $l, $p) {
parent::setData($h, $w, $l);
$this->price = $p;
}
//this is the function body of the parent abstract method
public function getPrice() {
return $this->price;
}
}
In the above example, the method getPrice() in class Furniture has been declared as Abstract. This means that its the responsibility of the child class to provide the functionality of getPrice(). The BookShelf class is a child of the Furniture class and hence provides the function body for getPrice().
Private methods cannot be abstract
If a method is defined as abstract then it cannot be declared as private (it can only be public or protected). This is because a private method cannot be inherited.
Interface Class
Interface is a class with no data members and contains only member functions and they lack its implementation. Any class that inherits from an interface must implement the missing member function body.
Interfaces is also an abstract class because abstract class always require an implementation.
In PHP 5, interfaces may declare only methods. An interface cannot declare any variables. To extend from an Interface, keyword implements is used. PHP5 supports class extending more than one interface.
Eg:
interface employee
{
function setdata($empname,$empage);
function outputData();
}
class Payment implements employee
{
function setdata($empname,$empage)
{
//Functionality
}
function outputData()
{
echo "Inside Payment Class";
}
}
$a = new Payment();
$a->outputData();
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home