Abstract Class is the way to achieve abstraction. It is a special class that never be instantiated directly. This class should contain at least one abstract method in it and mark by abstract keyword in the class definition. The main purpose of this class is to give a blueprint for derived classes and set some rules what the derived classes must implement when they inherit an abstract class. An abstract class can be used as a base class and all derived classes must implement the abstract definitions.
Syntax:
abstract class classname
{
// Method Declaration in abstract class
}
Here, the classname is the name of an abstract class. We can declare any number of methods inside it
Multiple-level Inheritance is a type of inheritance in which a derived class will inherit a base class and the derived class also behave like the base class to other class. For example, we have three classes named class1, class2, and class3. Here, class3 is derived from class2, and class2 is derived from class1.
Syntax:
class GFG : Abstract_Class
{
// Method definition for abstract method
}
MultiLevel Inheritance for Abstract Classes
Given an abstract class, our task is to implement the abstract class into the parent class and then implement the multilevel inheritance. So, let us understand with the help of an example.
class GFG : Abstract_class
{
// Method definition for abstract method
}
// First child class extends parent
class GFG2 : GFG
{
// Method definition
}
// Second child class extends first child class
class GFG3 : GFG2
{
// Method definition
}
Here, GFG is the parent class and GFG2 and GFG3 are the child class that extends the parent class.
Example:
C#
using System;
abstract class Abstract_class
{
public abstract void abstract_method();
}
class GFG : Abstract_class
{
public override void abstract_method()
{
Console.WriteLine( "Abstract method is called" );
}
}
class GFG2 : GFG
{
public void Mymethod1()
{
Console.WriteLine( "Method from GFG2 class" );
}
}
class GFG3 : GFG2
{
public void Mymethod2()
{
Console.WriteLine( "Method from GFG3 class" );
}
}
class Geeks{
public static void Main(String[] args)
{
GFG3 obj = new GFG3();
obj.abstract_method();
obj.Mymethod1();
obj.Mymethod2();
}
}
|
Output:
Abstract method is called
Method from GFG2 class
Method from GFG3 class
Explanation: In this example, we created an Abstract class named “Abstract_class” and declared a method named “abstract_method” inside it. Then we created a parent class named “GFG” by overriding the method of an abstract class. After that, we created the first child class named “GFG2” that inherits the parent class and defined a method named “Mymethod1” inside it. Then created a second child class named “GFG3” that inherits the first child class and defined a method “Mymethod2” inside it. Finally, we created the main class that includes the main method, then created an object(named “obj”) for the second child class and called all the methods that are declared and get the output on the screen.