Wednesday, October 5, 2011

abstract class example and Interfaces


In the above case figure is an abstract class that provides the attributes, which are required in common for multiple figure like – rectangle, circle, triangle, cone etc. so it provide reusability through inheritance.
The Figure class also contains two abstract methods which need to be implimented separately for each figure, without changing the signature of the method.

- Add a class Figure.cs and write the following 
    public abstract class Figure
    {
        public double width, height, radius;
        public const float pi = 3.14f;
        public abstract double GetArea();
        public abstract double GetPerimeter();
    }

- Add a class Rectangle.cs and write the following :
  public  class Rectangle : Figure
    {
       public Rectangle(double width, double height)
       {
       // here using base or this will be same
           base.width = width;
           this.height = height;
          
       }

       public override double GetArea()
       {
           return width * height;
       }
       public override double GetPerimeter()
       {
           return 2 * (height + width);
       }
    }

- Add a class Circle.cs and write the following :
    class Circle: Figure
    {
       public Circle (double radius)
       {
           base.radius = radius;
       }

       public override double GetArea()
       {
           return pi * radius * radius;
       }
       public override double GetPerimeter()
       {
           return 2 * pi *radius;
       }
    }

- To consume the Figures add a class TestFigure.cs and write the following:
    class TestFigure
    {
        static void Main()
        {
            Rectangle r = new Rectangle(12.9, 23.87);
            Console.WriteLine(r.GetArea());
            Console.WriteLine(r.GetPerimeter());
            Circle c = new Circle (229.32);
            Console.WriteLine(c.GetArea());
            Console.WriteLine(c.GetPerimeter());
            Console.ReadLine();
        }
    }


INTERFACES  -  These are also types just like a class but can contain only abstract members init.

Non abstract class –
                                                - only non abstract members

Abstract class –
                                                -  abstract members
                                            -  non abstract members

Interfaces  –
                                                - only abstract members

Note – whatever rules and regulations we have discussed in case of abstract classes applies to interfaces also.
Interfaces are used in the development of distributed applications Clint sever technology. 
Interfaces also provide support for multiple inheritances i.e. a class can inherit from any number of Interfaces but can have only one class as its parent.

SEALED CLASS AND ABSTRACT CLASS


Sealed Class a class which can’t be inherited by any other class is referred as a Sealed Class. To make a class Sealed we need to apply sealed modifier on it.


Syntax -
sealed class Class1
{
- members
}
class Class2 : Class1    // invalid

Note – a sealed class if required can be consumed from other classes by creating its object.

Sealed Methods 
       A method which cannot be overridden under a child class is referred as a sealed method. By default every method is sealed method because overriding a method is not possible unless it was declared as virtual.
            If at all a method is declared as virtual within a class any of its child class in the linear hierarchy has a chance to override the method.
   Eg.
class Class1
public virtual void Display()

class Class2 : Class1
public override void Display()

class Class3 : Class2
public override void Display()

A virtual method of a class can be sealed by its child class so that further overriding of the method by Childs of child class will not be possible.
class Class1
public virtual void Display()

class Class2 : Class1
public sealed override void Display()

class Class3 : Class2
public override void Display()        // invalid

Abstract Methods and Abstract Class –


Abstract Method - A method without any method body is referred as an abstract method, what it has, is only Declearetion of the method. We need to use abstract modifier to declare an abstract method.

Abstract Class - the class under which these abstract methods are declared is referred as abstract class. Need to declare the class also using abstract modifier.
Ex-
abstract class Example   
{
public abstract void Add (int x , int y)
}

 the concept of abstract methods is near similar to the concept of method overriding, where in overriding if at all a class declared a method as virtual it can be re implemented by its child classes using the override modifier, which is only optional for a child class, whereas if any class declared a method as abstract implementation of the method has to be provided by its child classes using overrode modifier only, which is mandatory for child classes to provide the implementation
An abstract class can contain abstract and non- abstract members in it, if at all a class contains abstract members in it until and unless the abstract members are implemented under the childe class, childe class cannot consume non-abstract members of parent
 Note – An abstract class is never useable to itself because we cannot create the object of an abstract class. 
- Add a class AbsParent.cs and write the following code:
    abstract class AbsParent
    {
        public void Add(int x, int y)
    {
        Console.WriteLine(x + y);
    }
     public void sub(int x, int y)
        {
            Console.WriteLine(x - y);
        }
     public abstract void Mul(int x, int y);
     public abstract void Div(int x, int y);
    }
}

- Add a class AbsChild.cs and write the following code:
    class AbsChild : AbsParent
    {
        public override  void Mul(int x, int y)
    {
        Console.WriteLine(x * y);
    }
     public override void Div(int x, int y)
    {
        Console.WriteLine(x / y);
    }
        static void Main()
    {
            AbsChild obj = new AbsChild();
            obj.Add(100, 50); obj.sub(20, 10);

            obj.Mul(57, 29); obj.Div(1200, 600);
                Console.ReadLine();
        }

    }

- To test this rewrite the code under main method of class  AbsChild.cs as following:
{
            AbsChild obj = new AbsChild();
            AbsParent p = obj;
            p.Add(100, 50); p.sub(20, 10);

            p.Mul(57, 29); p.Div(1200, 600);
                Console.ReadLine();
        }

How to override the method in Polymorphism


How to override the method –

                If we want to override a method first under the parent class the method should be declared using virtual modifier, now the child class gets the permission to override the method which can be overridden by the child class using override modifier, but overriding the method is only optional for the child class.
eg – LoadParent
public virtual void test1(int x)
        LoadChild : LoadParent
public override void test1(int x)

Overriding is an option which allows to change the behavior of the parent class method under child class according to its requirement. To change the behavior parent class is giving the permission by declaring the method as virtual.

- To test this goes into the Class LoadParent and rewrite the Test method as following 
        public virtual void test1(int x)
        {
        Console.WriteLine("method test1");
        }

Now run the child class and check the result which also prove overriding is only optional.
- Add a new method under the class LoadChild as following
        public override void test1(int x)
        {
            Console.WriteLine("Method test 3");
        }

Now again run the child class and check the difference in result , where in the place of virtual method the overridden method gets executed, Because object of the child class gives First preference to Local methods .

After the child class is overriding a virtual method of its parent if required the child class has a chance to invoke virtual methods of Parent Class also, which can be done in two different ways –
  • By creating the object of parent class child class can invoke Parent class’s virtual method.

- To test this rewrites the code under main method of class LoadChild as following –
{
            LoadParent p = new LoadParent();
            LoadChild c = new LoadChild();
            p.test1(10);           // Invoke parent class method
            c.test1(10);           //Invoke child class method
            Console.ReadLine();
        }

Note – Earlier we have discussed references of parent class that are created using object of child class cannot invoke child class members but we have an assumption in overriding i.e. these references can invoke the overridden methods under child class because overriding is performed with the permission of parent.

To test this rewrites the code under main method of class LoadChild as following –
        {
           
            LoadChild c = new LoadChild();
            LoadParent p = c;      
            p.test1(10);           // Invokes child class method only
            c.test1(10);           //Invokes child class method
            Console.ReadLine();
        }

.       using base ‘keyword also from child class from child class we can invoke virtual methods of parent but using of “base and this key words” from a static block is invalid
To test the process add new method under child class as following –
        public void Ptest(int x)
        {
            base.test1(x);
        }

Now in the main method of Child class rewrite the code as following –
       {
           
            LoadChild c = new LoadChild();
            c.Ptest(10);            // Invokes Parent class method
            c.test1(10);           //Invokes child class method
            Console.ReadLine();
        }

Q. How to re-define a parent class method under child class –
Ans – A parent class method can be re- defined under its child class using two different approaches
  • Method overriding
  • Method Hiding
  1. In the first case parent class gives the permission for child class to re-define its method by declaring it as virtual, now he child class can re-define the method using override modifier.
  2. In the second case parent class doesn’t give any permission to re-define its method to the child class, but still the child class can re-define it without any permission of its parent.

LoadParent

public void show()
public virtual void test (int x)

LoadChild : LoadParent

public    new   void  show()               // method hiding
public    override   void   test (int x)   // method overriding
To test this add new method under the class load child as following-
        public new void show ()
        {
            Console.WriteLine("Method show 2");
        }

All the rules we have discussed in case of overriding applies to method hiding also accept reference of parent class created from object of Child can invoke overridden methods of child but not the methods which are re-implemented using method hiding approach.
To check this rewrite the code under main method of class load child as following-
        {
           
            LoadChild c = new LoadChild();
            LoadParent p = c;      
            p.show();        // Invokes parent method because this is method hiding
            c.test(10);     //Invokes child method because this is method overriding
            Console.ReadLine();
        }

Polymorphism is of two types
  1. Static or compile time polymorphism.
  2. Dynamic or run time polymorphism.

In the first case the object of class recognizes which Polymorphic method it has to call at the time of compilation of the program only, which is possible in overloading.
In the second case the object of a class recognizes which Polymorphic method it has to call at run time of while executing the program, this happen in case of method overriding and method hiding.

POLYMORPHISM:


POLYMORPHISM:- 
.       Entities behaving in different ways depending upon the input it receives is known as polymorphism  i.e. whenever the input changes the output or behavior of entity also changes , this can be implemented with an approach known as-
  1. overloading  and
  2. overriding
     Overloading –

                It is an approach which allows defining multiple methods with the same name with in a class, but signature of the method should be different. Signature in the sense we can either change the type of parameter being pass to the method or number of parameter being pass to the method or order of parameter being pass to the method.
public void show()
public void show(int x)
public void show(string s)
public void show(int x , string s)
public void show(string s, int x)
Note – Change in the return type of method is not taken into consideration in overloading.
-Add a class LoadDemo.cs and write the following:
    class LoadDemo
    {
        public void show()
        {
            Console.WriteLine(1);
       
        }
        public void show(int x)
        {
            Console.WriteLine(2);

        }
        public void show(string s)
        {
            Console.WriteLine(3);

        }
        public void show(int x, string s)
        {
            Console.WriteLine(4);

        }
        public void show(string s, int x)
        {
            Console.WriteLine(5);

        }
        static void Main()
        {
            LoadDemo d = new LoadDemo();
            d.show(); d.show(10); d.show("Hello");
            d.show(10, "hello"); d.show("hello", 10);
            Console.ReadLine();
        }
    }

As discussed earlier whenever you changed the type of input applied to a method automatically a different method get executed that matches with the given type performing a different action.
                Overloading is an approach which allows you to provide multiple behaviors to a methodexample – the WriteLine method that is defined with 19 different behaviors which can print any type of value i.e. supplies to it.

Constructor Overloading  Just like we can overload methods in the same way constructors of a class also can be overloaded, when a class contain multiple constructor in it we can use  any constructor to create object of that class.
-Add a class LoadCon.cs and write the following:
using System;

namespace oopsProject
{
    class LoadCons
    {
        int x;
        public LoadCons()
        {
            this.x = x;
        }
     
       public LoadCons(int x)
       {
           x = 100;
       }
               
        public void Display()
        {
            Console.WriteLine();
        }
       static void Main()
        {
            LoadCons c1 = new LoadCons();
            LoadCons c2 = new LoadCons(100);
            c1.Display(); c2.Display();

            Console.ReadLine();
        }
    }

}


We overload constructors of a class so that the variables of class can be initialized with either default values or by a given value supplied to the constructor as in our above example......

Inheritance Based overloading
                  If at all a method which is declared under parent class is overloaded in the child class we called it as inheritance based overloading.

-Add a class LoadParent.cs and write the following:
using System;

namespace oopsProject
{
    class LoadParent
    {
        public void show()
        {
            Console.WriteLine("Method Show1");
        }
      
        public void test1(int x)
        {
            Console.WriteLine("method test1");
        }   
    }
}


-Add a class Class1.cs and write the following:
    class LoadChild : LoadParent
    {
        public void test2(string s)
        {
            Console.WriteLine("Method test2");
        }
        static void Main()
        {
            LoadChild c = new LoadChild();
            c.show(); c.test1(10); c.test2("hello");
            Console.ReadLine();
        }
   
    }


Method overriding

        If at all a parent class method is redefined under the child class with the same signature we call it as method overriding.
Differences between overloading and overriding
overloading
overriding
         it’s an approach of defining multiple methods with same name changing their signature
         It’s an approach of defining multiple methods with same name same signature.
         this can be done with in class as well as within the child class also
         This can be done only on the child class.
         To overload a parent class method under child we don’t required any perdition from parent.
         To override a parent class method under child we required an explicit permission from parent.