1 / 50

Object Oriented Programming

Object Oriented Programming. Advanced Concepts. Svetlin Nakov. Telerik Corporation. www.telerik.com. Table of Contents. Inheritance What is Inheritance? Inheritance H ierarch y Transitive Inheritance Encapsulation and Data Abstraction Cohesion and Coupling Polymorphism

Download Presentation

Object Oriented Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object Oriented Programming Advanced Concepts Svetlin Nakov Telerik Corporation www.telerik.com

  2. Table of Contents • Inheritance • What is Inheritance? • Inheritance Hierarchy • Transitive Inheritance • Encapsulation and Data Abstraction • Cohesion and Coupling • Polymorphism • Abstract Classes • Virtual Methods

  3. Inheritance Howand When to Use It?

  4. What is Inheritance? • The ability of a class to implicitly gain all members of another class • The class that gains new functionality is called derived class • The class whose methods are inherited is calledbaseclass to his derived class • Inheritance establishes an is-a relationship between classes: A is B

  5. How to Define Inheritance? • We must specify the name of the base class after the name of the derived • In the constructor of the derived class we use the keyword base to invoke the constructor of the base class public class Shape {...} public class Circle : Shape {...} public Circle (int x, int y) : base(x) {...}

  6. Simple Inheritance Example public class Mammal { private int age; public Mammal(int age) { this.age = age; } public int Age { get { return age; } set { age = value; } } public void Sleep() { Console.WriteLine("Shhh! I'm sleeping!"); } }

  7. Simple Inheritance Example (2) public class Dog : Mammal { private string breed; public Dog(int age, string breed) : base(age) { this.breed = breed; } public string Breed { get { return breed; } set { breed = value; } } public void WagTail() { Console.WriteLine("Tail wagging..."); } }

  8. Simple Inheritance Live Demo

  9. Inheritance Hierarchy • Usinginheritance we create inheritance hierarchy • Easily represented by UML class diagrams • Classes are represented by rectangles containing the methods and data that belong to them • Relations between classes are represented by arrows

  10. Class Diagram – Example struct interface Shape Point ISurfaceCalculatable #mPosition:Point +CalculateSurface:int +mX:int +mY:int +Point struct Square Rectangle Color -mSize:int -mWidth:int -mHeight:int +mRedValue:byte +Square +mGreenValue:byte +CalculateSurface:int +Rectangle +mBlueValue:byte +CalculateSurface:int +Color FilledSquare FilledRectangle -mColor:Color -mColor:Color +FilledSquare +FilledRectangle 10

  11. 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 typeand types derived from it • internal – access is limited to the current assembly • protectedinternal– access is limited to the current assembly or types derived from the containing class

  12. Important Aspects • Structures cannot be inherited • In C# there is no multiple inheritance • Instance constructors, destructors, and static constructors are not inherited • Inheritance is transitive. • If C is derived from B, and B is derived from A, then C inherits A as well

  13. Transitive Inheritance class Creature { public void Walk() { Console.WriteLine("Walking ...."); } } class Mammal : Creature { //The same as Simple Inheritance Example… } class Dog : Mammal { //The same as Simple Inheritance Example… }

  14. Transitive Inheritance (2) class MainClass { static void Main() { Dog Joe = new Dog(6, "labrador"); Joe.Walk(); } } class MainClass { static void Main() { Dog Joe = new Dog(6, "labrador"); Joe.Walk(); } }

  15. Transitive Inheritance LiveDemo

  16. Important Features • A derived class extends itsbase class • It can add new members but cannot remove derived ones • A derived class can hide inherited members by declaring new members with the same name or signature • A class can declare virtual methods and properties • Derived classes can override theimplementation of these members

  17. Encapsulation and Data Abstraction

  18. Encapsulation • Encapsulation is one of the basic principles when using objects and inheritance • Encapsulation is the ability to hide the internal data and methodsof an object • So that only the essential for using it parts to be programmatically accessible • The exact implementation of methods and data members remains hidden • Only vital information about the object is presented

  19. Data Abstraction • The ability to work with data without concern about its exact implementation, knowing only the operations we can perform on it • Data abstraction simplifies the programming process • Data abstraction usually imitates well known processes from the real world

  20. Cohesion and Coupling

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

  22. Good and Bad Cohesion • Good: hard disk, cdrom, floppy • BAD: spaghetti code

  23. Strong Cohesion • Strong cohesion example • Class Math that has methods: Sin(), Cos(), Asin() Sqrt(), Pow(), Exp() Math.PI, Math.E double sideA = 40, sideB = 69; double angleAB = Math.PI / 3; double sideC = Math.Pow(sideA, 2) + Math.Pow(sideB, 2) - 2 * sideA * sideB * Math.Cos(angleAB); double sidesSqrtSum = Math.Sqrt(sideA) + Math.Sqrt(sideB) + Math.Sqrt(sideC);

  24. Bad Cohesion • Bad cohesion example • Class Magic that has these methods: • Another example: public void PrintDocument(Document d); public void SendEmail(string recipient, string subject, string text); public void CalculateDistanceBetweenPoints(int x1, int y1, int x2, int y2) MagicClass.MakePizza("Fat Pepperoni"); MagicClass.WithdrawMoney("999e6"); MagicClass.OpenDBConnection();

  25. 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 • 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

  26. Loose and Tight Coupling • 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?

  27. Loose Coupling - Example class Report { public bool LoadFromFile(string fileName) {…} public bool SaveToFile(string fileName) {…} } class Printer { public static int Print(Report report) {…} } class Program { static void Main() { Report myReport = new Report(); myReport.LoadFromFile("C:\\DailyReport.rep"); Printer.Print(myReport); } }

  28. Tight Coupling - Example class MathParams { public static double operand; public static double result; } class MathUtil { public static void Sqrt() { MathParams.result = CalcSqrt(MathParams.operand); } } // … static void Main() { MathParams.operand = 64; MathUtil.Sqrt(); Console.WriteLine(MathParams.result); } }

  29. Spaghetti Code • Combination of bad cohesion and tight coupling: class Report { public void Print() {…} public void InitPrinter() {…} public void LoadPrinterDriver(string fileName) {…} public bool SaveReport(string fileName) {…} public void SetPrinter(string printer) {…} } class Printer { public void SetFileName() {…} public static bool LoadReport() {…} public static bool CheckReport() {…} }

  30. Polymorphism

  31. Polymorphism • Polymorphism is the ability for classes to provide different implementations of methods called by the same name • It allows a method of a class to react differently depending on the object it is used on • Polymorphism allows change in implementation of virtual methods • Polymorphism in components is usually implementedthrough abstract classes and virtual methods

  32. Abstract Class • An abstract class is a class that cannot be instantiated itself – it must be inherited • Some or all members of the class can be unimplemented, the inheriting class must provide implementation • Members that are implemented might still be overridden using the keyword override

  33. 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 • Methods that are declared as virtual in a base class can be overridden using the keyword overridein the derived class public virtual void CalculateSurface()

  34. The overrideModifier • Usingoverridewe can modify a method or property • An override method provides a new implementation of a member inherited from a base class • You cannot override a non-virtual or static method • The overridden base method must be virtual, abstract, or override

  35. Polymorphism – Example class Creature { public virtual void Speak() {} } class Cat : Creature { public override void Speak() { Console.WriteLine("Miaaay!"); } } class Dog : Creature { public override void Speak() { Console.WriteLine("Bark, bark, Grrrr!"); } }

  36. Polymorphism – Example (2) static void Main() { Creature[] creatures = new Creature[] { new Dog(), new Cat() }; foreach (Creature animal in creatures) { string name = animal.GetType().Name; Console.WriteLine("{0}: ", name); animal.Speak(); } }

  37. Polymorphism LiveDemo

  38. Abstract Classes – Example public abstract class Animal { abstract public int Speed { get; } } public class Cheetah : Animal { public override int Speed { get { return 100; } } } public class Turtle : Animal { public override int Speed { get { return 1; } } }

  39. Abstract Classes – Example (2) static void Main() { Turtle snail = new Turtle(); int speed = snail.Speed; Console.Write("Thr turtle can go{0}km/h", speed); Console.WriteLine(); Cheetah cheetah = new Cheetah(); speed = cheetah.Speed; Console.Write("The cheetah can go {0}km/h", speed); Console.WriteLine(); }

  40. Abstract Classes LiveDemo

  41. When to Use Polymorphism? • When you need a group of components with identical functionality • When you need base classesto remain easily modifiable and flexible • Polymorphism require more designing • best used in small-scale development tasks

  42. Summary • Inheritance – one of the basic characteristics of OOP • Inheritance hierarchy visualization and design • Basic inheritance practices – abstraction and encapsulation • Basic inheritance characteristics – cohesion and coupling • Polymorphism – when and why to use it

  43. Object Oriented Programming ? Questions? ? ? ? ? ? ? ? ? ? ?

  44. Exercises • 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.

  45. Exercises (2) 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. 2. Define 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. This method must return the surface of the figure

  46. Exercises (3) (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. 3. Write a program that tests the behavior of the CalculateSurface() method for different shape(Circle, Rectangle, Triangle) objects, stored in an array.

  47. Exercises (5) 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 thatidentifies the animal by its sound.

  48. Exercises (6) 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.

  49. Exercises (7) 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.

  50. Exercises (8) 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.

More Related