Interface

Syntax & Properties of interface

void main() {
  // Interfaces in dart
}

abstract class A {
  String a;

  void testA1();

  void testA2() {
    print("A2");
  }
}

abstract class B {
  void testB1();

  void testB2() {
    print("B2");
  }
}

class C implements A, B {
  @override
  void testB1() {}

  @override
  void testB2() {}

  @override
  String a;

  @override
  void testA1() {}

  @override
  void testA2() {}
}

Dart implicitly defines a class as an interface, hence called as implicit interface . As there is no interface keyword , implicitly all classes are interfaces . Note: This might change in the future

You can implement multiple interfaces at once

Whenever you implement a interface you must override everything inside it

Interface : Why we use them -1 ?

import 'dart:math';

void main() {
  // Interface is generally used with abstract Class
  // Though dart gives us the flexibility to use it with 
  // normal class , most of the time it will be used with abstract class 

  
  double area(Shape shape){

  
    return shape.calarea();
    
  }
  
  print(area(Square(10)));
  
}

abstract class Shape {
 
  void draw();

  double calarea();
}

class Circle implements Shape{
  int radius;

  @override
  void draw() {
    print("Drawing a Circle");
  }

  @override
  double calarea() {
    return pi*pow(this.radius,2);
  }

  Circle(this.radius);
}

class Square implements Shape {
  double length;

  @override
  void draw() {
    print("Drawing a Square");
  }

  @override
  double calarea() {
    return pow(this.length, 2);
  }

  Square(this.length);

Interface : Why we use them -2 ?

void main(){
  
  
  var purchase1 = Purchase();
  
  purchase1.pay(Bkash());
  
}



abstract class PaymentInterface{
  
  void payment();
  
  
}

class Bkash implements PaymentInterface{
  
  @override
  void payment(){
    
    print("Bkash");
    // Logic for payment using Bkash 
  }
  
}


class Rocket implements PaymentInterface {
  
  @override
  void payment(){
    
    print("Rocket");
    // Logic for payment using Rocket
  }
  
}

class Visa implements PaymentInterface{
  
  @override
  void payment(){
    
    print("Visa");
    // Logic for payment using Visa
  }
  
}


class Cash implements PaymentInterface{
  
  @override
  void payment(){
    
    print("Cash");
    // Logic for payment using Cash 
  }
  
}

//--------------------


class Purchase{
  
  void pay(PaymentInterface paymenttype){
    
    
    
    paymenttype.payment();
    
    //Payment Logic for a product purchase 
    
  }
  
}

Though dart gives us the flexibility to implement any class , most of the time you are going to implement abstract classes containing abstract methods (i.e. turning those abstract classes into interfaces )

Last updated