Abstract Class
- Abstract Class
- Why we need an abstract class?
- Rules for Abstract classes
A class can be declared as abstract without having an abstract method.
If a class have an abstract method then it must be declared abstract.
Abstract class cannot be instantiated which means you cannot create an object of it, but it can be extended.
An abstract class can also include normal or concrete methods.
We use abstract keyword to declare an abstract class.
A class derived from the abstract class must implement all those methods that are declared as abstract in the parent class.
- Example
Abstract Class in Dart is a class that has at least one abstract method.
Abstract method is a method declared without implementation.
A class that is declared using abstract keyword is known as abstract class. It can have abstract methods(methods without body) as well as concrete methods (regular methods with body). A normal class(non-abstract class) cannot have abstract methods.
An abstract class can not be instantiated, which means you are not allowed to create an object of it. It can only be extended by the subclass, and the subclass must be provided the implantation to the abstract methods which are present in the superclass.
Syntax :
//body
}
Let's say we have a class "Person" that has method "nativeHi" and the subclasses of it like "French","German","English" etc.
Since the person nativeHi differs from one person to another, there is no point to implement this method in parent class.
This is because every child class must override this method to give its own implementation details, like "French" class will say "salut" in this method and "German" class will say "hallo".
Thus, making this method abstract would be the good choice as by making this method abstract we force all the sub classes to implement this method( otherwise you will get compilation error), also we don't need to give any implementation to this method in parent class.
abstract class Person {
void nativeHi();
}
class French extends Person {
void nativeHi() {
print("salut");
}
}
class English extends Person {
void nativeHi() {
print("hi");
}
}
class German extends Person {
void nativeHi() {
print("hallo");
}
}
void main() {
var f = French(), e = English(), g = German();
f.nativeHi();
e.nativeHi();
g.nativeHi();
}
hi
hallo