Ad Code

Responsive Advertisement

ABSTRACT CLASS EXAMPLE AND INTERFACES

ABSTRACT CLASS

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.

Reactions

Post a Comment

0 Comments