Presentation is loading. Please wait.

Presentation is loading. Please wait.

Advanced Concepts Svetlin Nakov Telerik Corporation www.telerik.com.

Similar presentations


Presentation on theme: "Advanced Concepts Svetlin Nakov Telerik Corporation www.telerik.com."— Presentation transcript:

1 Advanced Concepts Svetlin Nakov Telerik Corporation www.telerik.com

2 1. Inheritance  What is Inheritance?  Inheritance Hierarchy  Transitive Inheritance 2. Encapsulation and Data Abstraction 3. Cohesion and Coupling 4. Polymorphism  Abstract Classes  Virtual Methods 2

3 How and When to Use It?

4  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 called base class to his derived class  Inheritance establishes an is-a relationship between classes: A is B 4

5  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 5 public class Shape {...} public class Circle : Shape {...} public Circle (int x, int y) : base(x) {...}

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

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

8 Live Demo

9  Using inheritance 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 9

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

11  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 11

12  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 12

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

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

15 Live Demo

16  A derived class extends its base 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 the implementation of these members 16

17

18  Encapsulation is one of the basic principles when using objects and inheritance  Encapsulation is the ability to hide the internal data and methods of 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 18

19  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 19

20

21  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 21

22  Good: hard disk, cdrom, floppy  BAD: spaghetti code 22

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

24  Bad cohesion example  Class Magic that has these methods:  Another example: 24 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 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 25

26  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? 26

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

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

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

30

31  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 implemented through abstract classes and virtual methods 31

32  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 32

33  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 override in the derived class 33 public virtual void CalculateSurface()

34  Using override we 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 34

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

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

37 Live Demo

38 38 public abstract class Animal { abstract public int Speed abstract public int Speed { get; get; }} public class Cheetah : Animal { public override int Speed public override int Speed { get { return 100; } get { return 100; } }} public class Turtle : Animal { public override int Speed public override int Speed { get { return 1; } get { return 1; } }}

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

40 Live Demo

41  When you need a group of components with identical functionality  When you need base classes to remain easily modifiable and flexible  Polymorphism require more designing  best used in small-scale development tasks 41

42  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 42

43 Questions?

44 1.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. 44

45 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 45

46 (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. (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. 46

47 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. 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. 47

48 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. 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. 48

49 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. 49

50 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. 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. 50


Download ppt "Advanced Concepts Svetlin Nakov Telerik Corporation www.telerik.com."

Similar presentations


Ads by Google