• What is the use of “Final class” and can a final class be an abstract?

      0 comments


    The “Final” keyword is used to make the class uninheritable. So the class or it’s methods can not be overridden.

    final class Class1 {
        // ...
    }
    
    class FatalClass extends Class1 {
        // ...
    }
    
    $out= new FatalClass();
    

    An Abstract class will never be a final class as an abstract class must be extendable.

  • Explain abstract class and its behaviour?

      0 comments

    Abstract class is defined as a solitary entity, so other classes can inherit from it. An abstract  class can not be instantiated, only the subclasses of it can have instances. Following is one of the best examples to explain the use of an abstract class and the behavior of it.

     class Fruit {
     private $color;
    
     public function eat() {
      //chew
     }
    
      public function setColor($c) {
       $this->color = $c;
      }
     }
    
     class Apple extends Fruit {
      public function eat() {
       //chew until core
      }
     }
    
     class Orange extends Fruit {
      public function eat() {
       //peel
       //chew
      }
     }
    

    Now taste an apple

    $apple = new Apple();
    $apple->eat();
    

    What’s the taste of it? Obviously it’s apple

    Now eat a fruit

    $fruit = new Fruit();
    $fruit->eat();
    

    What’s the taste of it? It doesn’t make any sense. does it? Which means the class fruit should not be Instantiable . This is where the abstract class comes into play

    abstract class Fruit {
     private $color;
    
     abstract public function eat()
    
     public function setColor($c) {
      $this->color = $c;
     }
    }