Showing posts with label abstract class. Show all posts
Showing posts with label abstract class. Show all posts

Saturday, 5 June 2021

Php: Abstract classes

Abstract class can have the methods without implementation.

 

Can an abstract class has both abstract and concrete methods (Methods with definition/body)?

Yes

 

Can I create an object to the abstract class?

No

 

How to create an abstract class?

‘abstract’ keyword is used to define an abstract class.

 

Syntax

abstract class ClassName{
    
}

Example

abstract class Logger{
    public function log($msg){
        echo $msg;
    }

    public abstract function debug($msg);
    public abstract function info($msg);
    public abstract function error($msg);
}


In the above example.

a.   log is a concrete method

b.   debug, info and error are abstract methods.

 

How to define abstract method?

Syntax

abstract access_specifier function_name(args){
    
}


Example

abstract public function log();


Another concrete class can extend this abstract class and provide implementation to the abstract methods.

 

abstract_class_demo.php

#!/usr/bin/php

<?php

    abstract class Logger{
        public function log($msg){
            echo $msg;
        }

        public abstract function debug($msg);
        public abstract function info($msg);
        public abstract function error($msg);
    }
    
    class MyLogger extends Logger{
        public function debug($msg){
            $this->log($msg);
        }

        public function info($msg){
            $this->log($msg);
        }

        public function error($msg){
            $this->log($msg);
        }
    }

    $logger = new MyLogger();

    $logger->log("Simple log\n");
    $logger->debug("Debug log\n");
    $logger->info("Info log\n");
    $logger->error("Error log\n");
?>


Output

$ ./abstract_class_demo.php 

Simple log
Debug log
Info log
Error log


Note

a.   If class ‘C’ extending an abstract class ‘A’, then class ‘C’ must provide implementation to all the abstract methods of class ‘A’, else make the class ‘C’ as abstract.





 

  

Previous                                                    Next                                                    Home

Tuesday, 23 January 2018

Kotlin: Abstract classes

An abstract class can have methods without implementation. Abstract class is defined using ‘abstract’ keyword.

Ex
interface Arithmetic{
 fun sum(x : Int, y : Int) : Int
 fun sub(x : Int, y : Int) : Int
 fun mul(x : Int, y : Int) : Int
 fun div(x : Int, y : Int) : Int
}

abstract class ArithmeticImpl : Arithmetic{
 override fun sum(x : Int, y : Int) : Int{
  return x + y
 }
 
 override fun sub(x : Int, y : Int) : Int{
  return x - y
 }
}

You can’t define instance (object) to abstract class.

Abstract method
Just like how you defined abstract class, you can define abstract method (method without implementation) using the keyword ‘abstract’.

abstract class ArithmeticImpl : Arithmetic{
 override fun sum(x : Int, y : Int) : Int{
  return x + y
 }
 
 override fun sub(x : Int, y : Int) : Int{
  return x - y
 }
 
 abstract fun areaofCircle(radius : Int) : Int
}

In the above snippet, I declared ‘areaOfCircle’ as abstract method. Any concrete class that is extending this abstract class must provide implementation to all the abstract methods.


class ConcreteArithmetic : ArithmeticImpl() {
 override fun mul(x: Int, y: Int): Int {
  return x * y
 }

 override fun div(x: Int, y: Int): Int {
  return x / y
 }

 override fun areaofCircle(radius: Int): Double {
  return 3.14 * radius * radius
 }
}

Find the below working application.


HelloWorld.kt

interface Arithmetic {
 fun sum(x: Int, y: Int): Int
 fun sub(x: Int, y: Int): Int
 fun mul(x: Int, y: Int): Int
 fun div(x: Int, y: Int): Int
}

abstract class ArithmeticImpl : Arithmetic {
 override fun sum(x: Int, y: Int): Int {
  return x + y
 }

 override fun sub(x: Int, y: Int): Int {
  return x - y
 }

 abstract fun areaofCircle(radius: Int): Double
}

class ConcreteArithmetic : ArithmeticImpl() {
 override fun mul(x: Int, y: Int): Int {
  return x * y
 }

 override fun div(x: Int, y: Int): Int {
  return x / y
 }

 override fun areaofCircle(radius: Int): Double {
  return 3.14 * radius * radius
 }
}

fun main(args: Array<String>) {
 var obj = ConcreteArithmetic()

 var sumOf10And20 = obj.sum(10, 20)
 var subOf10And20 = obj.sub(10, 20)
 var mulOf10And20 = obj.mul(10, 20)
 var divOf10And20 = obj.div(10, 20)
 var areaOfCircle = obj.areaofCircle(5)

 println("sumOf10And20 = $sumOf10And20")
 println("subOf10And20 = $subOf10And20")
 println("mulOf10And20 = $mulOf10And20")
 println("divOf10And20 = $divOf10And20")
 println("areaOfCircle = $areaOfCircle")

}


Output

sumOf10And20 = 30
subOf10And20 = -10
mulOf10And20 = 200
divOf10And20 = 0
areaOfCircle = 78.5






Previous                                                 Next                                                 Home

Friday, 21 February 2014

Abstract Methods and Abstract Classes

Abstract Method
An abstract method is a method that is declared without an implementation. An abstract method is declared using the keyword abstract.

Syntax
abstract returnType methodName(parameters)

Example
abstract int sum(int operand1, int operand2);

Abstract Class
An abstract class is declared using the keyword abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

Syntax
    abstract class ClassName{
        /* may or may not contain abstract methods */
    }

If a class extends the abstract class, then it must provide the implementation for all the abstract methods in the abstract class, otherwise the class should be declared as abstract.

The main purpose of abstract class is to use the common code in the sub classes.

Example
abstract class Animal{
 String name;

 String getName(){
  return name;
 }

 void setName(String name){
  this.name = name;
 }

 abstract String run();
}

class Elephant extends Animal{
 String run(){
  return "I can run at the speed of 25 mph";
 }
}
   
class Lion extends Animal{
 String run(){
  return " I can run at the speed of 50 mph";
 }
}
     
class Tiger extends Animal{
 String run(){
  return "I can run at the speed of 60 mph";
 }
}
     
class AbstractTest{
 public static void main(String args[]){
  Animal anim1 = new Elephant();
  anim1.setName("Gaja");
  System.out.println(anim1.getName() +":" + anim1.run());

  anim1 = new Lion();
  anim1.setName("Aslam");
  System.out.println(anim1.getName() +":" + anim1.run());

  anim1 = new Tiger();
  anim1.setName("PTR");
  System.out.println(anim1.getName() +":" + anim1.run());
 }
}


Output
Gaja:I can run at the speed of 25 mph
Aslam: I can run at the speed of 50 mph
PTR:I can run at the speed of 60 mph

Every Animal has a name, so getName() and setName() are common to all the animals, So the implementation for these methods kept in the abstract class Animal. Where as different Animals runs at different speeds, so the run() method declared as abstract, so all the concrete classes that are extending the class Animal, must provide the implementation for the run method.

Some Points to Remember
1. Can I create constructor inside the abstract class ?
Yes, but you can't initialize an object for the abstract class.

Example
abstract class Animal{
 String name; 

 Animal(String name){
  this.name = name;
 }
}
 
2. Can I make abstract class as final ?
No, If you make abstract class as final, then no other class can able to extend it. So, compiler throws error. Abstract and final can't be used together.

Example
final abstract class Animal{
 String name; 

 Animal(String name){
  this.name = name;
 }
}
 

When you tries to compile the above program, compiler throws the below error.
 Animal.java:1: error: illegal combination of modifiers: abstract and final
    final abstract class Animal{
    ^
    1 error


3. Can I make abstract method as final ?
No, If you make abstract method as final, then no other class can able to override it. So, compiler throws error. Abstract and final can't be used together.

Example
abstract class Animal{
 String name; 

 final abstract void run();

 }
}

When you tries to compile the above program, compiler throws the below error.
Animal.java:4: error: illegal combination of modifiers: abstract and final
final abstract void run();
^
1 error
 

4. Can I define main method in abstract class ?
Yes, it is valid, but creation of object to the abstract is not possible.

Example
abstract class Animal{
 String name; 

 public static void main(String args[]){
  System.out.println("I am in main method");
 }
}
   
Output
I am in main method

5. What is wrong with the below program ?
    abstract class Animal{
        void run();
    }

Above program won't compile, since if you want to make a method as abstract, then it must be declared with the specifier abstract. When you tries to compile, compiler throws the below error.

Animal.java:2: error: missing method body, or declare abstract
void run();
^
1 error

To make the program run you have two options.

Option 1
    Make the method as abstract.

    abstract class Animal{
        abstract void run();
    }

Option 2
provide the implementation for the method run().

    abstract class Animal{
        void run(){
        }
    }
  
6. An abstract class allowed to have static methods, where as interfaces have instance methods only (From Java8 onwards, we can add static methods to interfaces).

7. The methods declared in interface are abstract by default.

8. Can an interface has constructor ?
No

9. Can an abstract class have a final method?
Yes, it can. But the final method cannot be abstract itself

Example
    abstract class Animal{
        final void print(){
            System.out.println(" I am final method in abstract class");
        }
    }


Final Classes and Methods                                                 Abstract Class vs Interface                                                 Home

Tuesday, 18 February 2014

Class inside an Interface

A class can be defined in an interface, By default the class defined in interface is public and static. Just like accessing the static final variables in the interface, we can access the class defined in the interface.

Example
interface InterfaceEx{
 double PI=3.142;
 
 class Employee{
  String firstName;
  String lastName;
 }

 String getEmployee();
 void setEmployee(Employee e);
}

class InterfaceExTest implements InterfaceEx{
 Employee emp;
 
 public String getEmployee(){
  return emp.firstName +"\t" + emp.lastName;
 }

 public void setEmployee(Employee emp){
  this.emp = emp;
 }

 public static void main(String args[]){
  Employee e1 = new Employee();
  e1.firstName = "abc";
  e1.lastName = "def";
  
  InterfaceExTest obj1 = new InterfaceExTest();
  obj1.setEmployee(e1);
  System.out.println(obj1.getEmployee());
 }
}
  
Output
abc def

Some points to Remember
1. A class defined in interface can implement the same interface.
interface InterfaceEx{

 class ClassInside implements InterfaceEx{
  public void print1(){
   System.out.println(" I am print1");
  }
 }
 
 void print1();
}

class InterfaceExTest{
 public static void main(String args[]){
  InterfaceEx.ClassInside e1 = new InterfaceEx.ClassInside();
  e1.print1();
 }
}

Output
I am print1

2. The class defined in an interface is public and static by default.

3. Can an abstract class defined in interface ?
Yes      
interface InterfaceEx{

 abstract class ClassInside implements InterfaceEx{
  public void print1(){
   System.out.println(" I am print1");
  }
 }
 
 void print1();
 void print2();
}

class InterfaceExTest{

 public static void main(String args[]){
  InterfaceEx.ClassInside e1 = new InterfaceEx.ClassInside(){
   public void print2(){
    System.out.println("I am in print2");
   }
  };
  
  e1.print1();
  e1.print2();
 }
}

Output
I am print1
I am in print2

4. Can I override the methods defined in the class, by the same class object ?
Yes, It is possible by using Anonymous classes.
Example
interface InterfaceEx{
 class ClassInside implements InterfaceEx{
  public void print1(){
   System.out.println(" I am print1");
  } 
  public void print2(){
   System.out.println(" I am print2");
  }
 }
 
 void print1();
 void print2();
}

class InterfaceExTest{
 public static void main(String args[]){
  InterfaceEx.ClassInside e1;
  e1 = new InterfaceEx.ClassInside(){
     public void print2(){
      System.out.println("Overriding print2");
     }
     
     public void print1(){
      System.out.println("Overriding print1");
     }
    };
    
  e1.print1();
  e1.print2();
 }
}
 
Output
Overriding print1
Overriding print2

As you see, the methods defined by the class “ClassInside” are overridden using Anonymous class.
.

Extend interface                                                 Interface in interface                                                 Home