Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
communitycreator

What are abstract classes in Dart?

Maria Elijah

Abstract class

In Dart, an abstract class is defined as a class that contains one or more abstract methodsmethods without implementation. The abstract keyword is used to declare abstract classes.

Methods that are declared but not implemented are known as abstract methods.

The concrete methods (also known as normal methods) are declared along with their implementation. Both kinds of methods can be found in an abstract class, but abstract methods cannot be found in a normal class.

Rules for an abstract class

  1. A class that contains an abstract method must be declared abstract, while a class that is declared abstract can have either abstract or concrete methods.

  2. If the class contains at least one abstract method, it must be declared abstract.

  3. The abstract class’s object cannot be created, but it can be extended.

  4. An abstract class is declared with the abstract keyword.

  5. Normal or concretemethod with the body methods can be included in an abstract class.

  6. The subclass must implement all of the parent class’s abstract methods.

How to declare an abstract class

abstract class ClassName {  
 // Body of abstract class  
}  

Suppose we have a class Shape that has properties such as height, width, and area() as methods, and we have classes Rectangle and Triangle. Each shape’s representation differs from the other.

Implementing area() in the parent class is unnecessary because each subclass must give its implementation of the parent class method. As a result, we may compel the subclass to implement that method, which is one of the advantages of abstract methods.

The parent class does not need to implement the given method.

The diagram below illustrates the implementation of an abstract class and its child classes.

Code

abstract class Shape { 
  //declaring propreties  
  int height;
  int width;
  
  //declaring abstract method  
  void area();    
}  

class Rectangle extends Shape{  
  Rectangle(int a, int b) {
    height = a;
    width = b;
  }
  // Overriding method 
  @override 
  void area() {  
    print("Area of rectangle is ${height * width}");  
  
  }  
  
}  
  
class Triangle extends Shape{  
   
  Triangle(int a, int b) {
    height = a;
    width = b;
  }
  // Overriding method
  @override
  void area() {  
    print("Area of triangle is ${height * width * 0.5}");  
  
  }  
  
}  
  
void main() {  

  // Creating Object of class Rectangle 
  Rectangle rect = new Rectangle(6, 3); 

  // Creating Object of class Triangle  
  Triangle triangle = new Triangle(21, 6);    
  
  rect.area();  
  triangle.area();  
}  

RELATED TAGS

dart
communitycreator
RELATED COURSES

View all Courses

Keep Exploring