SlideShare a Scribd company logo
Object-Oriented Programming Fundamental Concepts Svetlin Nakov Telerik Corporation www.telerik.com
Contents Fundamental Principles of OOP Inheritance Abstraction Encapsulation Polymorphism Cohesion and Coupling
Fundamental Principles of OOP
Fundamental Principles of OOP Inheritance Inherit members from parent class Abstraction Define and execute abstract actions Encapsulation Hide the internals of a class Polymorphism Access a class through its parent interface
Inheritance
Classes and Interfaces Classes define attributes and behavior Fields, properties, methods, etc. Methods contain code for execution Interfaces define a set of operations Empty methods and properties, left to be implemented later public class Labyrinth { … } public interface IFigure { … }
Inheritance Inheritance  allows  child  classes  inherits  the characteristics of existing  parent  class Attributes (fields and properties) Operations (methods) Child class can extend the parent class Add new fields and methods Redefine methods (modify existing behavior) A class can  implement   an interface by providing implementation for all its methods
Inheritance terminology derived class base class / parent class inherits derived interface base interface implements class interface implements
Inheritance – Benefits Inheritance has a lot of benefits Extensibility  Reusability Provides abstraction Eliminates redundant code 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 – Example Person +Name: String +Address: String Employee +Company: String +Salary: double Student +School: String Base class Derived class Derived class
Class Hierarchies Inheritance leads to a hierarchy of classes and/or interfaces in an application: … Game MultiplePlayersGame BoardGame Chess Backgammon SinglePlayerGame Minesweeper Solitaire …
Inheritance in .NET A class can inherit only one base class E.g.  IOException  derives from  SystemException  and it derives from  Exception A class can implement several interfaces This is  .NET’s  form of  multiple inheritance E.g.  List<T>  implements  IList<T> ,  ICollection<T> ,  IEnumerable<T> An interface can implement several interfaces E.g.  IList<T>  implements  ICollection<T>  and  IEnumerable<T>
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) {...}
Simple Inheritance Example public class Mammal { public int Age { get; set; } public Mammal(int age) { this.Age = age; } public void Sleep() { Console.WriteLine(&quot;Shhh! I'm sleeping!&quot;); } }
Simple Inheritance Example  (2) public class Dog : Mammal { public string Breed { get; set; } public Dog(int age, string breed) : base(age) { this.Breed = breed; } public void WagTail() { Console.WriteLine(&quot;Tail wagging...&quot;); } }
S imple  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
Inheritance and Accessibility class Creature { protected string Name { get; private set; } private void Talk() { Console.WriteLine(&quot;I am creature ...&quot;); } protected void Walk() { Console.WriteLine(&quot;Walking ...&quot;); } } class Mammal : Creature { // base.Talk() can be invoked here // this.Name can be read but cannot be modified here }
Inheritance and Accessibility (2) class Dog : Mammal { public string Breed { get; private set; } // base.Talk() cannot be invoked here (it is private) } class InheritanceAndAccessibility { static void Main() { Dog joe = new Dog(6, &quot;Labrador&quot;); Console.WriteLine(joe.Breed); // joe.Walk() is protected and can not be invoked // joe.Talk() is private and can not be invoked // joe.Name = &quot;Rex&quot;; // Name cannot be accessed here // joe.Breed = &quot;Shih Tzu&quot;; // Can't modify Breed } }
Inheritance and Accessibility Live Demo
Inheritance: I mportant  A spect s Structures  cannot be inherited  In C# there is no  multiple  inheritance Only multiple interfaces can be implemented Instance and static constructors are not inherited  Inheritance is  transitive  relation If C is derived from B, and B is derived from A, then C inherits A as well
Inheritance: Important Features A derived class extends its base class It can add new members but cannot remove derived ones Declaring new members with the same name or signature hides the inherited ones A class can declare  virtual  methods and properties Derived classes can  override  the implementation of these members E.g.  Object.Equals()  is virtual method
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 = managing complexity &quot;Relevant&quot; to what?
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 &quot;name&quot; but not &quot;color of eyes&quot; 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
In .NET abstraction is achieved in several ways: Abstract classes  Interfaces Inheritance Abstraction in .NET +Color : long ButtonBase +click() Control Button RadioButton CheckBox
Abstraction in .NET – Example System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.Control System.Windows.Forms.ButtonBase System.Windows.Forms.Button
Interfaces in C# An  interface  is a set of operations (methods) that given object can perform Also called &quot;contract&quot; for supplying a set of operations Defines abstract behavior Interfaces provide abstractions You shouldn't have to know anything about what is in the implementation in order to use it
Abstract Classes in C# Abstract classes are special classes defined with the keyword  abstract   Mix between class and interface Partially implemented or fully unimplemented Not implemented methods are declared  abstract  and are left empty Cannot be  instantiated Child classes should implement abstract  methods or declare them as  abstract
Abstract Data Types Abstract Data Types (ADT) are data types defined by a set of operations (interface) Example: LinkedList<T> +Add(item : Object) +Remove(item : Object) +Clear() … «interface» IList<T> List<T>
Inheritance Hierarchies Using inheritance we can create inheritance hierarchies Easily represented by UML class diagrams UML class diagrams Classes are represented by rectangles containing their methods and data Relations between classes are shown as arrows Closed triangle arrow means inheritance Other arrows mean some kind of associations
UML Class Diagram – Example Shape #Position:Point struct Point +X:int +Y:int +Point interface ISurfaceCalculatable +CalculateSurface:float Rectangle -Width:float -Height:float +Rectangle +CalculateSurface:float Square -Size:float +Square +CalculateSurface:float FilledSquare -Color:Color +FilledSquare struct Color +RedValue:byte +GreenValue:byte +BlueValue:byte +Color FilledRectangle -Color:Color +FilledRectangle
Class Diagrams in Visual Studio Live Demo
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 properties (read-only and read-write) No interface members should be hidden
Encapsulation – Example Data fields are private Constructors and accessors are defined (getters and setters) Person -name : string -age : TimeSpan +Person(string name, int age) +Name : string { get; set; } +Age : TimeSpan { get; set; }
Encapsulation in .NET Fields are always declared  private Accessed  through  properties  in read-only or read-write mode Constructors are almost always declared  public Interface methods are always  public Not explicitly declared with  public Non-interface   methods are declared  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 used Abstract operations are defined in the base class' interface and implemented in the child classes Declared as  abstract  or  virtual
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.  List<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 &quot;specialized&quot; later
Virtual M ethod s   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 public virtual void CalculateSurface()
The  override  Modifier 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
Polymorphism – How it Works? Polymorphism ensures that the appropriate method of the subclass is called through its base class' interface Polymorphism is implemented using a technique called  late method binding Exact method to be called is determined at  runtime , just before performing the call Applied for all  abstract  /  virtual  methods Note: Late binding is slower than normal (early) binding
Polymorphism – Example override CalcSurface()  { return size * size; } override CalcSurface()  { return PI * radius * raduis; } Abstract class Abstract action Concrete class Overriden action Overriden action Figure +CalcSurface() : double Square -x : int -y : int -size : int Circle -x : int -y : int -radius: int
Polymorphism – Example (2) abstract class Figure  {  public  abstract  double CalcSurface();  } abstract class Square  {  public  override  double CalcSurface() { return … } } Figure f1 = new Square(...); Figure f2 = new Circle(...); // This will call Square.CalcSurface() int surface = f1.CalcSurface(); // This will call Square.CalcSurface() int surface = f2.CalcSurface();
Polymorphism Live Demo
Class Hierarchies: Real World Example
Real World Example: Calculator Creating an application like the Windows Calculator Typical scenario for applying the object-oriented approach
Real World Example: Calculator (2) The calculator consists of controls: Buttons, panels, text boxes, menus, check boxes, radio buttons, etc. Class  Control  – the root of our OO hierarchy All controls can be painted on the screen Should implement an interface   IPaintable   with a method  Paint() Common properties: location, size, text, face color, font, background color, etc.
Real World Example: Calculator (3) Some controls 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 The  Calculator  itself is a  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 child controls inside it
Real World Example: Calculator (4) How a  Container  paints itself? Invokes  Paint()   for all controls inside it Each control knows how to visualize itself What is the common between buttons, check boxes and radio buttons? Can be pressed Can be selected We can define class  AbstractButton  and all buttons can derive from it
Calculator Classes  TextBox Paint() «interface» IPaintable -location -size -text -bgColor -faceColor -font Control Container Form Calculator AbstractButton Button CheckBox RadioButton MainMenu MenuItem Panel
Cohesion and Coupling
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 Well-defined abstractions keep cohesion strong Classes must contain strongly related functionality and aim for single purpose Cohesion is a useful tool for managing complexity
Good and Bad Cohesion Good: hard disk, cdrom, floppy BAD: spaghetti code
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);
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(&quot;Fat Pepperoni&quot;); MagicClass.WithdrawMoney(&quot;999e6&quot;); MagicClass.OpenDBConnection();
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
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?
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(&quot;C:\\DailyReport.rep&quot;); Printer.Print(myReport); } }
Tight Coupling – Example class MathParams { public static double operand; public static double result; } class MathUtil { public static void Sqrt() { MathParams.result = CalcSqrt(MathParams.operand); } }  class MainClass { static void Main() { MathParams.operand = 64; MathUtil.Sqrt(); Console.WriteLine(MathParams.result); } }
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() {…} }
Summary OOP fundamental principals are: inheritance, encapsulation, abstraction, polymorphism Inheritance allows inheriting members form another class Abstraction and encapsulation hide internal data and allow working through abstract interface Polymorphism allows working with objects through their parent interface and invoke abstract actions Strong cohesion and loose coupling avoid spaghetti code
Questions? Object-Oriented Programming Fundamental Concepts http://academy.telerik.com
Exercises 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.
Exercises (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.
Exercises (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.
Exercises (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.
Exercises (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.
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.
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.

More Related Content

What's hot (20)

Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
Riaj Uddin Mahi
 
Interface
InterfaceInterface
Interface
kamal kotecha
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Lovely Professional University
 
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Edureka!
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
Arati Gadgil
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
Darpan Chelani
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
Gil Fink
 
Clean code slide
Clean code slideClean code slide
Clean code slide
Anh Huan Miu
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
John Ferguson Smart Limited
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
baabtra.com - No. 1 supplier of quality freshers
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
Farooq Baloch
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Strings
StringsStrings
Strings
naslin prestilda
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
NexThoughts Technologies
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
Hawkman Academy
 

Viewers also liked (11)

08. Numeral Systems
08. Numeral Systems08. Numeral Systems
08. Numeral Systems
Intro C# Book
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
Intro C# Book
 
0. Course Introduction
0. Course Introduction0. Course Introduction
0. Course Introduction
Intro C# Book
 
17. Trees and Graphs
17. Trees and Graphs17. Trees and Graphs
17. Trees and Graphs
Intro C# Book
 
Technical Testing Introduction
Technical Testing IntroductionTechnical Testing Introduction
Technical Testing Introduction
Iosif Itkin
 
Oop’nin temel ilkeleri
Oop’nin temel ilkeleriOop’nin temel ilkeleri
Oop’nin temel ilkeleri
metehanates
 
Запознаване с Visual Basic. Основни форми и контроли
Запознаване с Visual Basic. Основни форми и контролиЗапознаване с Visual Basic. Основни форми и контроли
Запознаване с Visual Basic. Основни форми и контроли
Петя Газдова
 
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Isuru Perera
 
Компютърна система
Компютърна системаКомпютърна система
Компютърна система
Петя Газдова
 
Whatsapp's Architecture
Whatsapp's ArchitectureWhatsapp's Architecture
Whatsapp's Architecture
Udaya Kiran
 
WhatsApp architecture
WhatsApp architectureWhatsApp architecture
WhatsApp architecture
Mahesh Bitla
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
Intro C# Book
 
0. Course Introduction
0. Course Introduction0. Course Introduction
0. Course Introduction
Intro C# Book
 
17. Trees and Graphs
17. Trees and Graphs17. Trees and Graphs
17. Trees and Graphs
Intro C# Book
 
Technical Testing Introduction
Technical Testing IntroductionTechnical Testing Introduction
Technical Testing Introduction
Iosif Itkin
 
Oop’nin temel ilkeleri
Oop’nin temel ilkeleriOop’nin temel ilkeleri
Oop’nin temel ilkeleri
metehanates
 
Запознаване с Visual Basic. Основни форми и контроли
Запознаване с Visual Basic. Основни форми и контролиЗапознаване с Visual Basic. Основни форми и контроли
Запознаване с Visual Basic. Основни форми и контроли
Петя Газдова
 
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Isuru Perera
 
Whatsapp's Architecture
Whatsapp's ArchitectureWhatsapp's Architecture
Whatsapp's Architecture
Udaya Kiran
 
WhatsApp architecture
WhatsApp architectureWhatsApp architecture
WhatsApp architecture
Mahesh Bitla
 
Ad

Similar to 20. Object-Oriented Programming Fundamental Principles (20)

20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
maznabili
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental Concepts
Bharat Kalia
 
Object
ObjectObject
Object
Mohammad Mahdi Rahimi Moghadam
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
Ganesh Karthik
 
Better Understanding OOP using C#
Better Understanding OOP using C#Better Understanding OOP using C#
Better Understanding OOP using C#
Chandan Gupta Bhagat
 
Opps
OppsOpps
Opps
Lalit Kale
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
Sudarshan Dhondaley
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
PRIYACHAURASIYA25
 
CSharp_03_Inheritance_introduction_with_examples
CSharp_03_Inheritance_introduction_with_examplesCSharp_03_Inheritance_introduction_with_examples
CSharp_03_Inheritance_introduction_with_examples
Ranjithsingh20
 
Basic c#
Basic c#Basic c#
Basic c#
kishore4268
 
Object oriented programming inheritance
Object oriented programming inheritanceObject oriented programming inheritance
Object oriented programming inheritance
Renas Rekany
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
shubhra chauhan
 
Net Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdfNet Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdf
PavanNarne1
 
Module 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingModule 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented Programming
Prem Kumar Badri
 
C# interview
C# interviewC# interview
C# interview
Thomson Reuters
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop
Vladislav Hadzhiyski
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
frwebhelp
 
025 Summary.pdf
025 Summary.pdf025 Summary.pdf
025 Summary.pdf
OsamaAlsabaee2024
 
Object Oriented Programming C#
Object Oriented Programming C#Object Oriented Programming C#
Object Oriented Programming C#
Muhammad Younis
 
Inheritance
InheritanceInheritance
Inheritance
abhay singh
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
maznabili
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental Concepts
Bharat Kalia
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
Ganesh Karthik
 
CSharp_03_Inheritance_introduction_with_examples
CSharp_03_Inheritance_introduction_with_examplesCSharp_03_Inheritance_introduction_with_examples
CSharp_03_Inheritance_introduction_with_examples
Ranjithsingh20
 
Object oriented programming inheritance
Object oriented programming inheritanceObject oriented programming inheritance
Object oriented programming inheritance
Renas Rekany
 
Net Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdfNet Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdf
PavanNarne1
 
Module 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingModule 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented Programming
Prem Kumar Badri
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop
Vladislav Hadzhiyski
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
frwebhelp
 
Object Oriented Programming C#
Object Oriented Programming C#Object Oriented Programming C#
Object Oriented Programming C#
Muhammad Younis
 
Ad

More from Intro C# Book (20)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
Intro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
Intro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
Intro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
Intro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
Intro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
Intro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
Intro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 

Recently uploaded (20)

ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 

20. Object-Oriented Programming Fundamental Principles

  • 1. Object-Oriented Programming Fundamental Concepts Svetlin Nakov Telerik Corporation www.telerik.com
  • 2. Contents Fundamental Principles of OOP Inheritance Abstraction Encapsulation Polymorphism Cohesion and Coupling
  • 4. Fundamental Principles of OOP Inheritance Inherit members from parent class Abstraction Define and execute abstract actions Encapsulation Hide the internals of a class Polymorphism Access a class through its parent interface
  • 6. Classes and Interfaces Classes define attributes and behavior Fields, properties, methods, etc. Methods contain code for execution Interfaces define a set of operations Empty methods and properties, left to be implemented later public class Labyrinth { … } public interface IFigure { … }
  • 7. Inheritance Inheritance allows child classes inherits the characteristics of existing parent class Attributes (fields and properties) Operations (methods) Child class can extend the parent class Add new fields and methods Redefine methods (modify existing behavior) A class can implement an interface by providing implementation for all its methods
  • 8. Inheritance terminology derived class base class / parent class inherits derived interface base interface implements class interface implements
  • 9. Inheritance – Benefits Inheritance has a lot of benefits Extensibility Reusability Provides abstraction Eliminates redundant code 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)
  • 10. Inheritance – Example Person +Name: String +Address: String Employee +Company: String +Salary: double Student +School: String Base class Derived class Derived class
  • 11. Class Hierarchies Inheritance leads to a hierarchy of classes and/or interfaces in an application: … Game MultiplePlayersGame BoardGame Chess Backgammon SinglePlayerGame Minesweeper Solitaire …
  • 12. Inheritance in .NET A class can inherit only one base class E.g. IOException derives from SystemException and it derives from Exception A class can implement several interfaces This is .NET’s form of multiple inheritance E.g. List<T> implements IList<T> , ICollection<T> , IEnumerable<T> An interface can implement several interfaces E.g. IList<T> implements ICollection<T> and IEnumerable<T>
  • 13. 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) {...}
  • 14. Simple Inheritance Example public class Mammal { public int Age { get; set; } public Mammal(int age) { this.Age = age; } public void Sleep() { Console.WriteLine(&quot;Shhh! I'm sleeping!&quot;); } }
  • 15. Simple Inheritance Example (2) public class Dog : Mammal { public string Breed { get; set; } public Dog(int age, string breed) : base(age) { this.Breed = breed; } public void WagTail() { Console.WriteLine(&quot;Tail wagging...&quot;); } }
  • 16. S imple Inheritance Live Demo
  • 17. 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
  • 18. Inheritance and Accessibility class Creature { protected string Name { get; private set; } private void Talk() { Console.WriteLine(&quot;I am creature ...&quot;); } protected void Walk() { Console.WriteLine(&quot;Walking ...&quot;); } } class Mammal : Creature { // base.Talk() can be invoked here // this.Name can be read but cannot be modified here }
  • 19. Inheritance and Accessibility (2) class Dog : Mammal { public string Breed { get; private set; } // base.Talk() cannot be invoked here (it is private) } class InheritanceAndAccessibility { static void Main() { Dog joe = new Dog(6, &quot;Labrador&quot;); Console.WriteLine(joe.Breed); // joe.Walk() is protected and can not be invoked // joe.Talk() is private and can not be invoked // joe.Name = &quot;Rex&quot;; // Name cannot be accessed here // joe.Breed = &quot;Shih Tzu&quot;; // Can't modify Breed } }
  • 21. Inheritance: I mportant A spect s Structures cannot be inherited In C# there is no multiple inheritance Only multiple interfaces can be implemented Instance and static constructors are not inherited Inheritance is transitive relation If C is derived from B, and B is derived from A, then C inherits A as well
  • 22. Inheritance: Important Features A derived class extends its base class It can add new members but cannot remove derived ones Declaring new members with the same name or signature hides the inherited ones A class can declare virtual methods and properties Derived classes can override the implementation of these members E.g. Object.Equals() is virtual method
  • 24. 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 = managing complexity &quot;Relevant&quot; to what?
  • 25. 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 &quot;name&quot; but not &quot;color of eyes&quot; 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
  • 26. In .NET abstraction is achieved in several ways: Abstract classes Interfaces Inheritance Abstraction in .NET +Color : long ButtonBase +click() Control Button RadioButton CheckBox
  • 27. Abstraction in .NET – Example System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.Control System.Windows.Forms.ButtonBase System.Windows.Forms.Button
  • 28. Interfaces in C# An interface is a set of operations (methods) that given object can perform Also called &quot;contract&quot; for supplying a set of operations Defines abstract behavior Interfaces provide abstractions You shouldn't have to know anything about what is in the implementation in order to use it
  • 29. Abstract Classes in C# Abstract classes are special classes defined with the keyword abstract Mix between class and interface Partially implemented or fully unimplemented Not implemented methods are declared abstract and are left empty Cannot be instantiated Child classes should implement abstract methods or declare them as abstract
  • 30. Abstract Data Types Abstract Data Types (ADT) are data types defined by a set of operations (interface) Example: LinkedList<T> +Add(item : Object) +Remove(item : Object) +Clear() … «interface» IList<T> List<T>
  • 31. Inheritance Hierarchies Using inheritance we can create inheritance hierarchies Easily represented by UML class diagrams UML class diagrams Classes are represented by rectangles containing their methods and data Relations between classes are shown as arrows Closed triangle arrow means inheritance Other arrows mean some kind of associations
  • 32. UML Class Diagram – Example Shape #Position:Point struct Point +X:int +Y:int +Point interface ISurfaceCalculatable +CalculateSurface:float Rectangle -Width:float -Height:float +Rectangle +CalculateSurface:float Square -Size:float +Square +CalculateSurface:float FilledSquare -Color:Color +FilledSquare struct Color +RedValue:byte +GreenValue:byte +BlueValue:byte +Color FilledRectangle -Color:Color +FilledRectangle
  • 33. Class Diagrams in Visual Studio Live Demo
  • 35. 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 properties (read-only and read-write) No interface members should be hidden
  • 36. Encapsulation – Example Data fields are private Constructors and accessors are defined (getters and setters) Person -name : string -age : TimeSpan +Person(string name, int age) +Name : string { get; set; } +Age : TimeSpan { get; set; }
  • 37. Encapsulation in .NET Fields are always declared private Accessed through properties in read-only or read-write mode Constructors are almost always declared public Interface methods are always public Not explicitly declared with public Non-interface methods are declared private / protected
  • 38. 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
  • 40. 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 used Abstract operations are defined in the base class' interface and implemented in the child classes Declared as abstract or virtual
  • 41. 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. List<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 &quot;specialized&quot; later
  • 42. Virtual M ethod s 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 public virtual void CalculateSurface()
  • 43. The override Modifier 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
  • 44. Polymorphism – How it Works? Polymorphism ensures that the appropriate method of the subclass is called through its base class' interface Polymorphism is implemented using a technique called late method binding Exact method to be called is determined at runtime , just before performing the call Applied for all abstract / virtual methods Note: Late binding is slower than normal (early) binding
  • 45. Polymorphism – Example override CalcSurface() { return size * size; } override CalcSurface() { return PI * radius * raduis; } Abstract class Abstract action Concrete class Overriden action Overriden action Figure +CalcSurface() : double Square -x : int -y : int -size : int Circle -x : int -y : int -radius: int
  • 46. Polymorphism – Example (2) abstract class Figure { public abstract double CalcSurface(); } abstract class Square { public override double CalcSurface() { return … } } Figure f1 = new Square(...); Figure f2 = new Circle(...); // This will call Square.CalcSurface() int surface = f1.CalcSurface(); // This will call Square.CalcSurface() int surface = f2.CalcSurface();
  • 48. Class Hierarchies: Real World Example
  • 49. Real World Example: Calculator Creating an application like the Windows Calculator Typical scenario for applying the object-oriented approach
  • 50. Real World Example: Calculator (2) The calculator consists of controls: Buttons, panels, text boxes, menus, check boxes, radio buttons, etc. Class Control – the root of our OO hierarchy All controls can be painted on the screen Should implement an interface IPaintable with a method Paint() Common properties: location, size, text, face color, font, background color, etc.
  • 51. Real World Example: Calculator (3) Some controls 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 The Calculator itself is a 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 child controls inside it
  • 52. Real World Example: Calculator (4) How a Container paints itself? Invokes Paint() for all controls inside it Each control knows how to visualize itself What is the common between buttons, check boxes and radio buttons? Can be pressed Can be selected We can define class AbstractButton and all buttons can derive from it
  • 53. Calculator Classes TextBox Paint() «interface» IPaintable -location -size -text -bgColor -faceColor -font Control Container Form Calculator AbstractButton Button CheckBox RadioButton MainMenu MenuItem Panel
  • 55. 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 Well-defined abstractions keep cohesion strong Classes must contain strongly related functionality and aim for single purpose Cohesion is a useful tool for managing complexity
  • 56. Good and Bad Cohesion Good: hard disk, cdrom, floppy BAD: spaghetti code
  • 57. 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);
  • 58. 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(&quot;Fat Pepperoni&quot;); MagicClass.WithdrawMoney(&quot;999e6&quot;); MagicClass.OpenDBConnection();
  • 59. 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
  • 60. 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?
  • 61. 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(&quot;C:\\DailyReport.rep&quot;); Printer.Print(myReport); } }
  • 62. Tight Coupling – Example class MathParams { public static double operand; public static double result; } class MathUtil { public static void Sqrt() { MathParams.result = CalcSqrt(MathParams.operand); } } class MainClass { static void Main() { MathParams.operand = 64; MathUtil.Sqrt(); Console.WriteLine(MathParams.result); } }
  • 63. 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() {…} }
  • 64. Summary OOP fundamental principals are: inheritance, encapsulation, abstraction, polymorphism Inheritance allows inheriting members form another class Abstraction and encapsulation hide internal data and allow working through abstract interface Polymorphism allows working with objects through their parent interface and invoke abstract actions Strong cohesion and loose coupling avoid spaghetti code
  • 65. Questions? Object-Oriented Programming Fundamental Concepts http://academy.telerik.com
  • 66. Exercises 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.
  • 67. Exercises (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.
  • 68. Exercises (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.
  • 69. Exercises (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.
  • 70. Exercises (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.
  • 71. 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.
  • 72. 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.

Editor's Notes

  • #2: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.(c) 2006 National Academy for Software Development - http://academy.devbg.org* ## * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #4: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.(c) 2006 National Academy for Software Development - http://academy.devbg.org* ## * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #6: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.(c) 2006 National Academy for Software Development - http://academy.devbg.org* ## * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #10: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.(c) 2006 National Academy for Software Development - http://academy.devbg.org* ## Extensibility / Polymorphism: New functionality may be easily plugged in without changing existing classes as long the new plug-in classes extend given base classes. Reusability: For a set of similar applications a framework can be defined using a core set of classes that are to be extended by classes that fill in the application-dependent part. Information Hiding: If a more general class using a simpler contract is sufficient, details from extending classes may be hidden to some of the client classes. This allows them to be more independent from possible changes and diminishes the load of contracts that must be understood by a reader of these client classes. * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #24: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.(c) 2006 National Academy for Software Development - http://academy.devbg.org* ## * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #35: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.(c) 2006 National Academy for Software Development - http://academy.devbg.org* ## * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #40: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.(c) 2006 National Academy for Software Development - http://academy.devbg.org* ## * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #48: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.(c) 2006 National Academy for Software Development - http://academy.devbg.org* ## * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #49: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.(c) 2006 National Academy for Software Development - http://academy.devbg.org* ## * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##