What is Abstract Class?
Posted by Raj
Abstract Class:
To define a class as Abstract, the keyword abstract is to be used e.g. abstract class ClassName { }
<?php
abstract class AbstractClass
{
abstract protected function getValue();
abstract protected function setValue($val);
public function Display() {
print $this->getValue() . "\n";
}
}
class ChildClass1 extends AbstractClass
{
protected function getValue() {
return "ChildClass1";
}
public function setValue($val) {
return "ChildClass{$val}";
}
}
class ChildClass2 extends AbstractClass
{
public function getValue() {
return "ChildClass2";
}
public function setValue($val) {
return "ChildClass{$val}";
}
}
$class1 = new ChildClass1;
$class1->Display();
echo "<br>";
echo $class1->setValue('1') ."\n";
echo "<br>";
$class2 = new ChildClass2;
$class2->Display();
echo "<br>";
echo $class2->setValue('2') ."\n";
?>
To define a class as Abstract, the keyword abstract is to be used e.g. abstract class ClassName { }
- In abstract class at least one method must be abstract.
- we can create object of abstract class.
- Abstract classes may not be instantiated.
- The child classes which inherits the property of abstract base class, must define all the methods declared as abstract.
- Any class that contains at least one abstract method must also be abstract.
- If the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.
- Abstract class can contain variables and concrete methods.
- A class can Inherit only one Abstract class and Multiple inheritance is not possible for Abstract class.
<?php
abstract class AbstractClass
{
abstract protected function getValue();
abstract protected function setValue($val);
public function Display() {
print $this->getValue() . "\n";
}
}
class ChildClass1 extends AbstractClass
{
protected function getValue() {
return "ChildClass1";
}
public function setValue($val) {
return "ChildClass{$val}";
}
}
class ChildClass2 extends AbstractClass
{
public function getValue() {
return "ChildClass2";
}
public function setValue($val) {
return "ChildClass{$val}";
}
}
$class1 = new ChildClass1;
$class1->Display();
echo "<br>";
echo $class1->setValue('1') ."\n";
echo "<br>";
$class2 = new ChildClass2;
$class2->Display();
echo "<br>";
echo $class2->setValue('2') ."\n";
?>
This entry was posted on October 4, 2009 at 12:14 pm, and is filed under
OOP interview questions and answers,
PHP,
PHP interview questions and answers
.You can leave a response, or trackback from your own site.