Abstraction -  Using Abstract Class

Abstraction - Using Abstract Class


Abstraction -  Using Abstract Class


Abstraction is the process of hiding certain details and showing only essential information to the user.

Abstraction can be achieved with Abstract Class

Refer the below URL to achieve abstraction using Access modifiers.

https://itsforlavanya.blogspot.com/2020/08/abstraction-abstraction-in-c.html

Abstract Class - This is the class that cannot be instantiated, we cannot create an object of abstract class, it must be inherited from another class.

Abstract Method - This can be created only inside Abstract Class, and does not have a body(definition) , only declaration is allowed and the body is provided by  the class that inherits this class.

An Abstract class can have Abstract Method and Regular Methods.

using System;

 

namespace Abstraction

{

    // Abstract class

    abstract class Vehicle

    {

        // Abstract method (does not have a body)

        public abstract void twoWheeler();

        // Regular method

        public void start()

        {

            Console.WriteLine("Start the vehicle");

        }

    }

}


Now, if we try to create an object of Abstract Class Vehicle above, we get an error saying we cannot create instance of abstract class or interface

Vehicle obj = new Vehicle(); // Error -Cannot Create Instance of Abstract Class or Interface "Vehicle"


We use Override keyword before the abstract class method, when we are using it in inherited class.

public override void twoWheeler()


To access the abstract class, it should be inherited by another class like below


using System;

 

namespace Abstraction

{

    // Abstract class

    abstract class Vehicle

    {

        // Abstract method (does not have a body)

        public abstract void twoWheeler();

        // Regular method

        public void start()

        {

            Console.WriteLine("Start the vehicle");

        }

    }

 

    // Derived class (inherit from Animal)

    class TwoWheeler : Vehicle

    {

        public override void twoWheeler()

        {

            // The body of twoWheeler() is defined here

            Console.WriteLine("I got 2 wheels");

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            TwoWheeler obj = new TwoWheeler(); // Create a TwoWheeler object

            obj.twoWheeler();  // Call the abstract method

            obj.start();  // Call the regular method

        }

    }

}


Conclusion  - In abstract class we have not shown the implementation of twoWheeler method, this way we are hiding the implementation from outside world, and showing only required information.

    

 



0 comments: