Wednesday 10 September 2014

Abstract Class with example

Abstract Class:


An Abstract Class means that, no object of this class can be instantiated, but can make derivation of this. It can serve the purpose of base class only as no object of this class can be created.
Abstract Class is denoted by the keyword abstract.

Example:


abstract class myClass
{
      public myClass()
{
            // code to initialize the class…
}

      abstract public void anyMethod_01();
      abstract public void anyMethod_02(int anyVariable);
      abstract public int anyMethod_03 (int anyvariable);
}

It is important here to note that abstract classes can have non-abstract method(s), even can have only non-abstract method(s).

        abstract class myclass
        {
            public void nonAbstractMethod()
            {
                // code…
            }
        }

… is perfectly alright.
An abstract class can be derived from another abstract class. In that case, in the derived class, it is optional to implement the abstract method(s) of the base class.

Example:


 // Base abstract class
    abstract class baseClass
    {
        public abstract int addNumbers(int a, int b);
        public abstract int multiplyNumbers(int a, int b);
    }

    // Derived abstract class
    abstract class derivedClass : baseClass
    {
        // implementing addNumbers…
        public override int addNumbers(int a, int b)
        {
            return a + b;
        }

    }


// Derived class from 2nd class (derivedClass)
    class anyClass : derivedClass
    {
        // implementing multiplyNumbers of baseClass…
        public override int multiplyNumbers(int a, int b)
        {
            return a * b;
        }
    }

In the above example, we only implemented addNumbers in the derived abstract class (derivedClass). The abstract method multiplyNumbers is implemented in the anyClass, which is in turn derived fromderivedClass. 

0 comments:

Post a Comment