OOP Demo: Abstract Classes, Inheritance, Polymorphism, Encapsulation


In OOP, an abstract class is a class object that acts as the base/main class for all other classes to inherit from. In an abstract class, there is no implementation allowed, only declaration. Also, even if you make a constructor inside an abstract class, creating an instance of an abstract class is not allowed (i.e. if you try and do this, you will get compiler errors: A newObject = new A(); where A is an abstract class)

An abstract class is simply that of its namesake, its abstract. There’s nothing specific about it, but it will have properties and functions that other classes can use/have a relationship to the base abstract class object.

The following code shows an abstract class named Shape, with subclasses Square, Triangle, and Circle, who all use inheritance to inherit 1 function from the abstract class. All the subclasses will use the single function called ‘CalculateArea()’ where the polymorphism comes in. In C# when we inherit, the syntax is like so: class A : B, in Java when we inherit, the syntax is like so: class A extends B

  1. The step before the action.
  2. The action.
  3. The step after the action.

Polymorphism in a plain definition, is a function that can do different things depending on whichever class is using it. In other words: one function, many uses. In the example below, all objects implement a CalculateArea() function, note that finding the area for different shapes, the implementation is different, but the function name stays the same.

Encapsulation is simply protecting any properties, functions, or that is subject to change from outside code. We can also create a class object within a class object to hide an object from outside access that don’t need to use the object. In the example below, we give properties like length and width of a square to be private so that when we declare a Square object, we initialize using the public constructor like so: Shape square = new Square(l, w);

C#

abstract class Shape//this abstract Shape class is our base class to inherit from
    {//abstract classes are created by using the 'abstract' keyword
        public abstract int CalculateArea();
       /*abstract classes may or may not have abstract  functions/fields, in this case we'll make an abstract function called CalculateArea, and please look closely at the syntax in C#, if you're doing  Java it can be different.*/
    }
//we have a subclass called Square with its own unique characteristics, it inherits from Shape
    class Square : Shape
    {
        private int length;
        private int width;
        public Square() { }//empty constructor
        public Square(int length, int width)//overloading, we will pass in a length & width
        {
            this.length = length;
            this.width = width;
        }
        public override int CalculateArea()//pay close attention here: any functions inherited from an abstract or virtual class MUST contain the 'override' keyword
        {
            int area = this.length * this.width;
            return area;//and must return the same type
        }
    }
//the same routine is done for the next classes that inherit from Shape
    class Triangle : Shape
    {
        private int baseLength;
        private int height;
        public Triangle() { }
        public Triangle(int baseLength, int height)
        {
            this.baseLength = baseLength;
            this.height = height;
        }
        public override int CalculateArea()
        {
            int area = this.baseLength * this.height / 2;
            return area;
        }
    }
    class Circle : Shape
    {
        private double radius;
        public Circle() { }
        public Circle(double r)
        {
            this.radius = r;
        }
        public override int CalculateArea()
        {
            int area = (int)(Math.Pow(this.radius, 2) * Math.PI);
            return area;
        }
    }
class Program
{
     static void Main()
    {
//we create new objects of type shape and we initialise with a specific shape
            Shape square = new Square(5,10);
//so a Shape called square is initialised by giving by saying new Square(length, width)
//we do this because we want to create a new Shape and calculate its area by specifying that its a //square
//the same is done for the triangle and circle
            Shape triangle = new Triangle(10, 32);
            Shape circle = new Circle(7);

//we write out the areas of the shapes created
            Console.WriteLine("Area of square: {0} units", square.CalculateArea());
            Console.WriteLine("Area of triangle: {0} units", triangle.CalculateArea());
            Console.WriteLine("Area of circle: {0} units", circle.CalculateArea());

Console.ReadLine();//keep the window open
    }
}

C++

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <math.h>
#define PI 3.141592654
using namespace std;
class Shape
{
protected:
    int width;
    int height;
public:
    virtual int CalculateArea() = 0;
};

class Rectangle:public Shape
{
//private:
//    int width, height;
public:
    Rectangle(int w, int h)
    {
        this->width = w;
        this->height = h;
    }
    int CalculateArea()
    {
        return height * width;
    }
};
class Triangle:public Shape
{
public:
    Triangle(int base, int height)
    {
        this->width = base;
        this->height = height;
    }
    int CalculateArea()
    {
        return height * width / 2;
    }
};
class Circle:public Shape
{
private:
    double radius;
public:
    Circle(double r)
    {
        this->radius = r;
    }
    int CalculateArea()
    {
        return (int)(pow(this->radius, 2) * PI);
    }
};

int main()
{
    Shape* rect = new Rectangle(5,3);
    Shape* tri = new Triangle(10,25);
    Shape* c = new Circle(33.334);
    cout<<rect->CalculateArea()<<endl;
    cout<<tri->CalculateArea()<<endl;
    cout<<c->CalculateArea()<<endl;
    cin.get();
    return 0;
}

Java

import java.lang.Math;
abstract class Shape
{
    protected int width, height;
    public abstract int CalculateArea();
}
class Rectangle extends Shape
{
    public Rectangle(int w, int h)
    {
        this.width = w;
        this.height = h;
    }
    public int CalculateArea()
    {
        return width * height;
    }
}
class Triangle extends Shape
{
    public Triangle(int base, int h)
    {
        this.width = base;
        this.height = h;
    }
    public int CalculateArea()
    {
        return width * height / 2;
    }
}
class Circle extends Shape
{
    private double radius;
    public Circle(double r)
    {
        this.radius = r;
    }
    public int CalculateArea()
    {
        return (int)(Math.pow(radius, 2)*Math.PI);
    }
}

public class Program
{
     public static void main(String []args)
     {
        //note that in java when declaring/initializing class objects that
        //inherit a base class, you declare not using the base class name
        Rectangle r = new Rectangle(5,3);
        Triangle t = new Triangle(17,12);
        Circle c = new Circle(16.6667);
        System.out.println("Hello World");
        System.out.println(r.CalculateArea());
        System.out.println(t.CalculateArea());
        System.out.println(c.CalculateArea());
     }
}

An illustration of the hierarchy:

Advertisements

2 thoughts on “OOP Demo: Abstract Classes, Inheritance, Polymorphism, Encapsulation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s