In Dart, an abstract class is defined as a class that contains one or more 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.
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.
If the class contains at least one abstract method, it must be declared abstract.
The abstract class’s object cannot be created, but it can be extended.
An abstract class is declared with the abstract
keyword.
Normal or
The subclass must implement all of the parent class’s abstract methods.
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.
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
CONTRIBUTOR
View all Courses