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

Slides:



Advertisements
Similar presentations
Classes, Constructors, Properties, Events, Static Members, Interfaces, Inheritance, Polymorphism Svetlin Nakov Telerik Corporation
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
OOP: Inheritance By: Lamiaa Said.
Classes and Object- Oriented... tMyn1 Classes and Object-Oriented Programming The essence of object-oriented programming is that you write programs in.
Svetlin Nakov Telerik Corporation
Section 5 – Classes. Object-Oriented Language Features Abstraction –Abstract or identify the objects involved in the problem Encapsulation –Packaging.
Meeting #1 – November 2010 – Intro to C# Homework Assignments Svetlin Nakov Telerik Corporation
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Chapter 10 Classes Continued
Classes, Constructors, Properties, Events, Static Members, Interfaces, Inheritance, Polymorphism Technical Trainer Telerik Corporation
Object-Oriented Programming Fundamental Principles – Part I
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
2.5 OOP Principles Part 1 academy.zariba.com 1. Lecture Content 1.Fundamental Principles of OOP 2.Inheritance 3.Abstraction 4.Encapsulation 2.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Namespaces, Cohesion and Coupling Veselin Georgiev National Academy for Software Development academy.devbg.org Svetlin Nakov Telerik Corporation
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com.
2.5 OOP Principles Part 2 academy.zariba.com 1. Lecture Content 1.Polymorphism 2.Cohesion 3.Coupling 2.
Svetlin Nakov Telerik Corporation
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
Module 7: Essentials of Object-Oriented Programming.
Module 7: Object-Oriented Programming in Visual Basic .NET
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Inheritance, Abstraction, Encapsulation, Polymorphism
High-Quality Classes and Class Hierarchies Best Practices in Object-Oriented Design SoftUni Team Technical Trainers Software University
Encapsulation and Polymorphism Encapsulation, Polymorphism, Class Hierarchies, Cohesion and Coupling SoftUni Team Technical Trainers Software University.
Best Practices in the Object-Oriented Design Learning & Development Telerik Software Academy.
Inheritance, Abstraction, Encapsulation. 1. Fundamental Principles of OOP 2. Inheritance  Class Hierarchies  Inheritance and Access Levels 3. Abstraction.
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Peyman Dodangeh Sharif University of Technology Fall 2014.
Svetlin Nakov Telerik Software Academy Manager Technical Trainer
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Technical Trainer Software University
Salman Marvasti Sharif University of Technology Winter 2015.
Classes, Constructors, Properties, Events, Static Members, Interfaces, Inheritance, Polymorphism Doncho Minkov Telerik School Academy schoolacademy.telerik.com.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Introduction to Object-Oriented Programming Lesson 2.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Polymorphism, Class Hierarchies, Exceptions, Strong Cohesion and Loose Coupling Telerik Software Academy Object-Oriented Programming.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
© 2007 Lawrenceville Press Slide 1 Chapter 9 Inheritance  One class is an extension of another.  Allows a class to define a specialized type of an existing.
Inheritance and Abstraction Class Hierarchies, Abstract Classes, Interfaces SoftUni Team Technical Trainers Software University
Presented by Ted Higgins, SQL Server DBA An Introduction to Object – Oriented Programming.
Class Inheritance SWE 344 Internet Protocols & Client Server Programming.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Polymorphism, Class Hierarchies, Exceptions, Strong Cohesion and Loose Coupling.
Best Practices in the Object-Oriented Design Vesko Kolev Telerik Corporation
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
1 More About Derived Classes and Inheritance Chapter 9.
Encapsulation and Polymorphism
Advanced Programming in Java
Modern Programming Tools And Techniques-I
Object-Oriented Programming Concepts
Lecture 12 Inheritance.
Advanced Programming in Java
One class is an extension of another.
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Week 6 Object-Oriented Programming (2): Polymorphism
CIS 199 Final Review.
Chapter 11 Inheritance and Encapsulation and Polymorphism
Computer Science II for Majors
Presentation transcript:

Advanced Concepts Svetlin Nakov Telerik Corporation

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

How and When to Use It?

 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

 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) {...}

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

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

Live Demo

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

 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

 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

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

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(); }}

Live Demo

 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

 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

 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

 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

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

 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);

 Bad cohesion example  Class Magic that has these methods:  Another example: 24 public void PrintDocument(Document d); public void Send (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();

 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

 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

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

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

 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() {…}}

 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

 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

 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()

 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 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 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(); }}

Live Demo

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 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();}

Live Demo

 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

 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

Questions?

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

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

(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

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

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

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 Mortgage accounts have ½ interest for the first 12 months for companies and no interest for the first 6 months for individuals. 49

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