OBJECT ORIENTED PROGRAMMING

TABLE OF CONTENTS

  • Fundamental Principles of OOP
  • Inheritance
    • Class Hierarchies
    • Inheritance and Access modifiers
  • Abstraction
    • Interfaces
    • Abstract Classes
  • Encapsulation
  • Polymorphism
  • Cohesion and Coupling

Fundamental Principles of OOP

Fundamential principles of OOP

  • Inheritance
    - Inherit members from parent class
  • Abstraction
    - Define and execute abstract actions
  • Encapsulation
    - Hide internals of a class
  • Polymorphism
    - Access a class through its parent interface
  • Exception handling
  • Garbage collection

Classes and Interfaces

  • Classes define attributes and behavior
    • Fields, methods, etc.
    • Methods contain code for execution
  • Interfaces define a set of operations
    • Empty methods left to be implemented later

Classes and Interfaces (2)


interface ISampleInterface
{
    void SampleMethod();
}
class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation:
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }
    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();
        // Call the member.
        obj.SampleMethod();
    }
}
							

Inheritance (2)

  • Inheritance allows child classes to inherit the characteristics of an existing (base) superclass
    • Attributes(fields)
    • Operations(methods)
  • Child class can extend the superclass
    • Add new fields and methods
    • Redefine methods(modify existing behavior)
  • A class can implement an interface by providing implementation for all its methods

Inheritance (3)

  • Use inheritance for buidling is-a relationships
    - e.g. dog is-a animal(dogs are kind of animals)
  • Don't use it to build has-a relationship
    - e.g. dog has-a name(dog is not kind of name)
  • Inheritance has a lot of benefits
    - Extensibility
    - Reusability (code reuse)
    - Provides abstraction
    - Eliminates redundant code

Inheritance (4)

  • Inheritance implicitly gains all members from another class
    - All fields, methods,events, ...
    - Some members could be inaccessible (hidden)
  • The class whose methods are inherited is called super (base) class
  • The class that gains new functionality is called derived (child) class
  • Inheritance leads to a hierarchies of classes and / or interfaces in an application

Inheritance (5)

  • A class can inherit only one base class
  • Diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C.
  • If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?

Inheritance (6)

  • A class can implement several interfaces
    - This is our form of multiple inheritance
    
    class FirstAndSecond : BaseClass, IFirst, ISecond
    {
      // some stuff
    }
    									
  • An interface can inherit several interfaces as well
  • 
    public interface ICollection<T> : IEnumerable<T>, IEnumerable
    							

Access Modifiers

  • public - Access is not restricted.
  • protected - Access is limited to the containing class or types derived from the containing class.
  • internal - Access is limited to the current assembly.
  • protected internal - Access is limited to the current assembly or types derived from the containing class.
  • private - Access is limited to the containing type. Private members are accessible only within the body of the class or the struct in which they are declared.

Abstraction

Abstraction

  • Abstraction means ignoring irrelevant features, properties, or functions and emphasizing the relevant ones relevant to the given project
  • With an eye to future reuse in similar projects
  • Abstraction helps managing complexity

Abstraction (2)

  • Abstraction is something we do every day
    - Looking at an object, we see those things about it that have meaning to us
    - We abstract the properties of the object, and keep only what we need
    - e.g.students get "name" but not "color of eyes"
  • Allows us to represent a complex reality in terms of a simplified model
  • Abstraction highlights the properties of an entity that we need and hides the others

Abstraction (3)

    We can achieve abstraction in C# OOP in several ways:
  • Abstract classes
  • Interfaces
  • Inheritance

Interfaces

  • An interface defines a set of operations(methods) that given object should perform
    - Also called "contract" for providing a set of operations
    - Defines abstract behavior
  • Interfaces provide abstractions
    - You invoke the abstract actions
    - Without worrying how it is internally implemented

Interfaces (2)

  • Implementer classes must implement all interface methods
  • Interfaces describe a prototype of group of methods(operations), properties and events
    • Can be implemented by a given class
    • Define only the prototypes of the operations
    • No concrete implementation is provided
    • Can be used to define abstract data types
    • Can be inherited (extended) by other interfaces
    • Can not be instantiated

Abstract Class

    A class which contains the abstract keyword in its declaration is known as abstract class.
  • Abstract classes may or may not contain abstract methods e.g. methods without body
  • But, if a class have at least one abstract method, then the class must be declared abstract.

Abstract Class (2)

  • If a class is declared abstract it cannot be instantiated.
  • To use an abstract class you have to inherit it from another class, provide implementations to the abstract methods in it.
  • If you inherit an abstract class you have to provide implementations to all the abstract methods in it.

Abstract Methods

    If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.
  • You have to place the abstract keyword before the method name in the method declaration.

Abstract Methods (2)

  • abstract keyword is used to declare the method as abstract.
  • An abstract method contains a method signature, but no method body.
  • Instead of curly braces an abstract method will have a semi colon ( ; ) at the end

Abstract class or interface

    Here are some guidelines on when to use an abstract class and when to use interfaces in C#:
  • An abstract class is good if you think you will plan on using inheritance since it provides a common base class implementation to derived classes.
  • An abstract class is also good if you want to be able to declare non-public members. In an interface, all methods must be public.

Abstract class or interface (2)

  • If you think you will need to add methods in the future, then an abstract class is a better choice. Because if you add new method headings to an interface, then all of the classes that already implement that interface will have to be changed to implement the new methods. That can be quite a hassle.
  • Interfaces are a good choice when you think that the API will not change for a while.
  • Interfaces are also good when you want to have something similar to multiple inheritance, since you can implement multiple interfaces.

Encapsulation

Encapsulation

  • Encapsulation hides the implementation details
  • Class announces some operations (methods) available for its clients - its public interface
  • All data members (fields) of a class should be hidden
    - Accessed via read-only and read-write methods
  • No interface members should be hidden

Encapsulation (2)

  • Data fields are private
  • Constructors are almost always declared public
  • Interface methods are always public
  • Non-interface methods are declared it private / protected

Encapsulation - Benefits

  • Ensures that structural changes remain local:
    - Changing the class internals does not affect any code outside of the class
    - Changing methods' implementation does not reflect the clients using them
  • Encapsulation allows adding some logic when accessing client's data e.g. validation on modifying a property value
  • Hiding implementation details reduces complexity =>easier maintenance

Polymorphism

Polymorphism

  • Polymorphism - ability to take more than one form(objects have more than one type)
  • A class can be used through its parent interface
  • A child class may override some of the behaviors of the parent class
  • Polymorphism allows abstract operations to be defined and invoked
  • Abstract operations are defined in the base class' interface and implemented in the child classes - declared as abstract

Polymorphism (2)

    Why handle an object of given type as object of its base type?
  • To invoke abstract operations
  • To mix different related types in the same collection e.g. IList <Object> can hold anything
  • To pass more specific object to a method that expects a parameter of a more generic type
  • To declare a more generic field which will be initialized and "specialized" later

Method Overriding

    Runtime (Dynamic) Polymorhism
  • If a class inherits a method from its super class, then there is a chance to override the method provided that it is not marked final.
  • The benefit of overriding is: ability to define a behaviour that's specific to the subclass type which means a subclass can implement a parent class method based on its requirement.
  • In object-oriented terms, overriding means to override the functionality of an existing method.

Method Overriding (2)

    Rules for method overriding:
  • The argument list should be exactly the same as that of the overridden method.
  • The return type should be the same or a subtype of the return type declared in the original overridden method in the base class.
  • A method declared final cannot be overridden.
  • Constructors cannot be overridden.

Method Overloading

  • Compile time Polymorphism
  • A feature that allows a class to have two or more methods having same name, if their argument lists are different.

class Program
{
    static void Main(string[] args)
    {
        Add(3, 4);
        Add(3, 4, 3);
    }
    public static void Add(int FN, int SN)
    {
        Console.WriteLine("Total is {0}", FN + SN);
    }
    public static void Add(int FN, int SN, int TN)
    {
        Console.WriteLine("Total is {0}", FN + SN + TN);
    }
}
						

Cohesion and Coupling

Cohesion

    Cohesion describes
  • How closely the routines in a class or the code in a routine support a central purpose
  • Cohesion must be strong
  • Well-defined abstractions keep cohesion strong
  • Classes must contain strongly related functionality and aim for single purpose
  • Cohesion is a powerful tool for managing complexity

Cohesion (2)

  • Good cohesion: HDD, CD-ROM, remote control
  • Bad cohesion: spaghetti code (Combination of weak cohesion and tight coupling), single-board computer

Coupling

  • Coupling describes how tightly a class or routine is related to other classes or routines
  • Coupling must be kept loose
    • Modules must depend little on each other
    • Or be entirely independent (loosely coupled)
    • All classes / routines must have small, direct, visible, and flexible relationships to other classes / routines
    • One module must be easily used by other modules

Coupling (2)

  • Loose coupling: Easily place any HDD to another motherboard
  • Tight coupling:
    - Where is the video adapter?
    - Can you change the video controller?
office@e-dojo.it

EXERCISE

Problem 1: School classes

• We are given a school. In the school there are classes of students. Each class has a set of teachers. Each teacher teaches, a set of disciplines. Students have a name and unique class number. Classes have unique text identifier. Teachers have a name. Disciplines have a name, number of lectures and number of exercises. Both teachers and students are people. Students, classes, teachers and disciplines could have optional comments (free text block).
• Your task is to identify the classes (in terms of OOP) and their attributes and operations, encapsulate their fields, define the class hierarchy and create a class diagram with Visual Studio.

EXERCISE (2)

Problem 2: Students and workers

• Define abstract class Human with a first name and a last name. Define a new class Student which is derived from Human and has a new field — grade. Define class Worker derived from Human with a new property WeekSalary and WorkHoursPerDay and a method MoneyPerHourO that returns money earned per hour by the worker. Define the proper constructors and properties for this hierarchy.
• Initialize a list of 10 students and sort them by grade in ascending order (use LINQ or OrderBy() extension method).
• Initialize a list of 10 workers and sort them by money per hour in descending order.
• Merge the lists and sort them by first name and last name.

EXERCISE (3)

Problem 3: Animal hierarchy

• Create a hierarchy Dog, Frog, Cat, Kitten, Tomcat and define useful constructors and methods. Dogs, frogs and cats are Animals. All animals can produce sound (specified by the ISound interface). Kittens and tomcats are cats. All animals are described by age, name and sex. Kittens can be only female and tomcats can be only male. Each animal produces a specific sound.
• Create arrays of different kinds of animals and calculate the average age of each kind of animal using a static method (you may use LINQ).

EXERCISE (4)

Problem 4. Shapes

  • Define abstract class Shape with only one abstract method CalculateSurface() and fields width and height.
  • Define two new classes Triangle and Rectangle that implement the virtual method and return the surface of the figure (height * width for rectangle and height * width/2 for triangle).
  • Define class Square and suitable constructor so that at initialization height must be kept equal to width and implement the CalculateSurface() method.
  • Write a program that tests the behaviour of the CalculateSurface() method for different shapes (Square, Rectangle,Triangle) stored in an array.

EXERCISE (4)

Problem 5. Bank accounts

  • A bank holds different types of accounts for its customers: deposit accounts, loan accounts and mortgage accounts. Customers could be individuals or companies.
  • All accounts have customer, balance and interest rate (monthly based).
    • Deposit accounts are allowed to deposit and with draw money.
    • Loan and mortgage accounts can only deposit money.
  • All accounts can calculate their interest amount for a given period (in months). In the common case its is calculated as follows: number of months * interest rate.
  • Loan accounts have no interest for the first 3 months if are held by individuals and for the first 2 months if are held by a company.
  • Deposit accounts have no interest if their balance is positive and less than 1000.
  • Mortgage accounts have 1/2 interest for the first 12 months for companies and no interest for the first 6 months for individuals.
  • Your task is to write a program to model the bank system by classes and interfaces.
  • You should identify the classes, interfaces, base classes and abstract actions and implement the calculation of the interest functionality through overridden methods.