Object Oriented Programming Principles
Object Oriented Programming Principles
Object Oriented Programming Principles
Svetlin Nakov
Telerik Corporation
www.telerik.com
Contents
1. 2. 3. 4.
5.
6.
Polymorphism
Cohesion and Coupling
Inheritance
Inheritance
Inheritance
Child
Types of Inheritance
Inheritance terminology
derived class
inherits
class
implements
interface
derived interface
implements
base interface
Inheritance Benefits
Inheritance has a lot of benefits
Inheritance Example
Base class Person
+Name: String +Address: String
Derived class
Derived class
Employee
+Company: String +Salary: double
Student
+School: String
10
Class Hierarchies
Inheritance leads to a hierarchy
SinglePlayerGame
MultiplePlayersGame
Minesweeper
Solitaire
BoardGame
Chess Backgammon
11
Inheritance in .NET
Simple Inheritance
Live Demo
Accessibility Levels
Access modifiers in C#
public access is not restricted private access is restricted to the containing type protected access is limited to the containing type and types derived from it internal access is limited to the current assembly protected internal access is limited to the current assembly or types derived from the containing class
17
Abstraction
Abstraction
Abstraction
means ignoring irrelevant features, properties, or functions and emphasizing the relevant ones ...
"Relevant" to what?
= managing complexity
24
Abstraction (2)
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
25
Abstraction in .NET
In .NET abstraction
is achieved in several
ways:
Abstract classes Interfaces
Control +click()
Inheritance
ButtonBase +Color : long
26
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ButtonBase
System.Windows.Forms.Button
27
Interfaces in C#
An interface is a set of operations (methods)
You shouldn't have to know anything about what is in the implementation in order to use it
28
Abstract Classes in C#
Abstract
Not implemented methods are declared abstract and are left empty
Cannot be instantiated
Child
Data Types (ADT) are data types defined by a set of operations (interface)
interface IList<T> +Add(item : Object) +Remove(item : Object) +Clear()
Example:
LinkedList<T>
List<T>
30
Inheritance Hierarchies
Using inheritance we can create inheritance
hierarchies
Easily represented by UML class diagrams
UML class diagrams
struct Color
Encapsulation
Encapsulation
Encapsulation hides the implementation
details
Class All
announces some operations (methods) available for its clients its public interface
Encapsulation Example
Data fields are private Constructors
Encapsulation in .NET
Fields are always
declared private
public
Interface methods are
protected
Encapsulation Benefits
Ensures that structural
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
Hiding
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 (2)
Why handle an
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
41
Virtual Methods
Virtual method is method that can be used in
the same way on instances of base and derived classes but its implementation is different
A method is said
to be a virtual when it is
declared as virtual
public virtual void CalculateSurface()
declared as virtual in a base class can be overridden using the keyword override in the derived class
42
property
An override
method provides a new implementation of a member inherited from a base class a non-virtual or static method
abstract, or override
43
ensures that the appropriate method of the subclass is called through its base class' interface is implemented using a technique called late method binding
Exact method to be called is determined at runtime, just before performing the call
Polymorphism
(early) binding
Polymorphism Example
Abstract class
Figure +CalcSurface() : double
Abstract action
Concrete class
Overriden action
Overriden action
Polymorphism
Live Demo
49
of controls:
Buttons, panels, text boxes, menus, check boxes, radio buttons, etc.
Class
Common properties: location, size, text, face color, font, background color, etc.
50
could contain other (nested) controls inside (e. g. panels and toolbars)
We should have class Container that extends Control holding a collection of child controls
Form
Form is a special kind of Container Contains also border, title (text derived from Control), icon and system buttons
How the Calculator paints itself?
Invokes Paint() for all controls inside it Each control knows how to visualize itself
What is the common between buttons, check
Can be selected
We can define class
Calculator Classes
interface IPaintable Paint()
Control
-location -size -text -bgColor -faceColor -font
Container
AbstractButton
TextBox
MainMenu
MenuItem
Panel
Form
Button
CheckBox
RadioButton
Calculator
53
Cohesion
Cohesion describes how closely
all the routines in a class or all the code in a routine support a central purpose
Well-defined abstractions keep cohesion strong
Classes
must contain strongly related functionality and aim for single purpose complexity
55
56
Strong Cohesion
Strong cohesion example
Bad Cohesion
Bad cohesion example
Another example:
MagicClass.MakePizza("Fat Pepperoni"); MagicClass.WithdrawMoney("999e6"); MagicClass.OpenDBConnection();
58
Coupling
Coupling describes
All classes and routines must have small, direct, visible, and flexible relations to other classes and routines One module must be easily used by other modules
59
Loose Coupling:
Easily replace old HDD Easily place this HDD to another motherboard
Tight Coupling:
Where is the video adapter? Can you change the video controller?
60
Spaghetti Code
class Printer { public void SetFileName() {} public static bool LoadReport() {} public static bool CheckReport() {} }
63
Summary
Questions?
http://academy.telerik.com
Exercises
1.
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 name and unique class number. Classes have unique text identifier. Teachers have name. Disciplines have name, number of lectures and number of exercises. Both teachers and students are people. Your task is to identify the classes (in terms of OOP) and their attributes and operations, define the class hierarchy and create a class diagram with Visual Studio.
66
Exercises (2)
2.
Define class Human with first name and last name. Define new class Student which is derived from Human and has new field grade. Define class Worker derived from Human with new field weekSalary and work-hours per day and method MoneyPerHour() that returns money earned by hour by the worker. Define the proper constructors and properties for this hierarchy. Initialize an array of 10 students and sort them by grade in ascending order. Initialize an array of 10 workers and sort them by money per hour in descending order.
67
Exercises (3)
3.
Define abstract class Shape with only one virtual 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 Circle and suitable constructor so that on initialization height must be kept equal to width and implement the CalculateSurface() method. Write a program that tests the behavior of the CalculateSurface() method for different shapes (Circle, Rectangle, Triangle) stored in an array.
68
Exercises (4)
4.
Create a hierarchy Dog, Frog, Cat, Kitten, Tomcat and define suitable constructors and methods according to the following rules: all of this are Animals. 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 produce a sound. Create arrays of different kinds of animals and calculate the average age of each kind of animal using static methods. Create static method in the animal class that identifies the animal by its sound.
69
Exercises (5)
5.
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.
70
Exercises (6)
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 interest for the first 12 months for companies and no interest for the first 6 months for individuals.
71
Exercises (7)
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.
72