Friday, November 17, 2017

What is Abstract Class - Facts About Abstract Class


  • What is Abstract Class  ?

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation

Abstract classes may not be instantiated, and require sub -classes to provide implementations for the abstract methods.


  • Why do we need  Abstract Class ?

-   While you want to implementation detail to your child class but don't allow child to create instance      of  your class.  

-   We need to use abstract class when we want to follow certain hierarchy for all sub classes.

-   In simple words, it is a kind of contract that forces all the sub classes to carry on the same                    hierarchies or standards.

  • Facts About Abstract Class

- Abstract class can not be Sealed or static.

- We Can not create instance of the abstract class.

- An abstract class can have abstract as well as non abstract methods. 

- Abstract members can only be declared inside an abstract class

- An abstract member cannot be static or private

- A concrete class cannot inherit more than one abstract class, in other words multiple Inheritance is     not possible.


  • Practical Example For  Abstract Class using c# console application 

We will take example of of Apple. for example if we take Apple class has our base class have some basic functionality like "Call" and "SMS". Sub Classes can use this two method. We will define GetModelName method as  abstract and force sub classes to provide implementation for this method.

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    abstract class Apple
    {
        public void call()
        {
            // Non Abstract Method All SubClass can use without implementaion 
            Console.WriteLine("Call Method: This method provides Calling features");
            Console.WriteLine("Abstrac class called");
        }

        // Abstract Method Sub Classes must provide implementaion for this abstract method.
        public abstract string GetModelName();

        // Non Abstract Property 
        public string ModelName { get; set; }

        // Abstract Method
        public abstract string IMEI { get; }

    }

    class IPhone4 : Apple
    {
        // Implementaion of Abstract Property.
        public override string IMEI
        {
            get
            {
                return "34234324324324";
            }

        }

        // Implementaion of Abstract Method
        public override string GetModelName()
        {
            return "Iphone4";
        }

        static void Main(string[] args)
        {
            IPhone4 obj = new IPhone4();
            obj.call();
            obj.ModelName = obj.GetModelName();
        }
    }
}









No comments:

Post a Comment

Featured Post