SlideShare a Scribd company logo
1 of 70
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 
2
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 
4 
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 
5
Types of Inheritance 
 Inheritance terminology 
derived class 
base class / 
inherits parent class 
class implements interface 
derived interface implements base interface 
6
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) 
7
Inheritance – Example 
Person 
+Name: String 
+Address: String 
Derived class Derived class 
Employee 
+Company: String 
+Salary: double 
Base class 
Student 
+School: String 
8
Class Hierarchies 
 Inheritance leads to a hierarchy of classes 
and/or interfaces in an application: 
9 
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> 
10
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 
11 
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("Shhh! I'm sleeping!"); 
} 
} 
12
Simple Inheritance Example 
p(ub2l)ic class Dog : Mammal 
{ 
public string Breed { get; set; } 
public Dog(int age, string breed) 
: base(age) 
{ 
this.Breed = breed; 
} 
public void WagTail() 
{ 
Console.WriteLine("Tail wagging..."); 
} 
} 
13
Simple 
InhLeivre iDetmaonce
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 
15
Inheritance and 
class Accessibility Creature 
{ 
protected string Name { get; private set; } 
private void Talk() 
{ 
Console.WriteLine("I am creature ..."); 
} 
protected void Walk() 
{ 
Console.WriteLine("Walking ..."); 
} 
} 
class Mammal : Creature 
{ 
// base.Talk() can be invoked here 
// this.Name can be read but cannot be modified here 
} 
16
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, "Labrador"); 
Console.WriteLine(joe.Breed); 
// joe.Walk() is protected and can not be invoked 
// joe.Talk() is private and can not be invoked 
// joe.Name = "Rex"; // Name cannot be accessed here 
// joe.Breed = "Shih Tzu"; // Can't modify Breed 
} 
} 
17
Inheritance and 
AcceLsivse iDebmiolity
Inheritance: Important 
Aspects  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 
19
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 
20
Abstraction
Abstraction 
 Abstraction means ignoring irrelevant 
features, properties, or functions and 
emphasizing the relevant ones ... 
"Relevant" to what? 
 ... relevant to the given project (with an eye 
to future reuse in similar projects) 
 Abstraction = managing complexity 
22
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 "name" but not "color of eyes" 
 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 
23
Abstraction in .NET 
 In .NET abstraction is achieved in several 
ways: 
 Abstract classes 
 Interfaces 
 Inheritance 
Control 
+click() 
ButtonBase 
+Color : long 
Button RadioButton CheckBox 
24
Abstraction in .NET – 
Example 
25 
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 "contract" 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 
26
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 
27
Abstract Data Types 
 Abstract Data Types (ADT) are data types 
defined by a set of operations (interface) 
«interface» 
 Example: 
IList<T> 
+Add(item : Object) 
+Remove(item : Object) 
+Clear() 
… 
LinkedList<T> 
List<T> 
28
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 
29
UML Class Diagram – Example 
30 
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 
33
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; } 
34
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 
35
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 
36
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 
38
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 "specialized" later 
39
Virtual Methods 
 Virtual method is method that can be used in 
the same way on instances of base and 
derived classes but its implementation is 
different 
 A method is said to be a virtual when it is 
declared as virtual 
public virtual void CalculateSurface() 
 Methods that are declared as virtual in a base 
class can be overridden using the keyword 
override in the derived class 40
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 
41
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 
42
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 
43
Polymorphism – Example (2) 
44 
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 
47
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. 
48
Real World Example: Calculator 
 So(m3e) 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 
49
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 
50
Calculator Classes 
51 
TextBox 
«interface» 
IPaintable 
Paint() 
Control 
-location 
-size 
-text 
-bgColor 
-faceColor 
-font 
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 
53
Good and Bad Cohesion 
 Good: hard disk, cdrom, floppy 
 BAD: spaghetti code 
54
Strong Cohesion 
 Strong cohesion example 
 Class Math that has methods: 
Sin(), Cos(), Asin() 
Sqrt(), Pow(), Exp() 
Math.PI, Math.E 
55 
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: 
56 
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();
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 
57
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? 
58
Loose Coupling – Example 
class Report 
{ 
public bool LoadFromFile(string fileName) {…} 
public bool SaveToFile(string fileName) {…} 
} 
class Printer 
{ 
public static int Print(Report report) {…} 
} 
class Program 
{ 
static void Main() 
{ 
Report myReport = new Report(); 
myReport.LoadFromFile("C:DailyReport.rep"); 
Printer.Print(myReport); 
} 
} 
59
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); 
} 
} 
60
Spaghetti Code  Combination of bad cohesion and tight coupling: 
61 
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 
62
Object-Oriented Programming 
Fundamental Concepts 
Questions? 
http://academy.telerik.com
Exercises 
1. We are given a school. In the school there are classes of 
students. Each class has a set of teachers. Each teacher 
teaches a set of disciplines. Students have name and 
unique class number. Classes have unique text 
identifier. Teachers have name. Disciplines have name, 
number of lectures and number of exercises. Both 
teachers and students are people. 
Your task is to identify the classes (in terms of OOP) 
and their attributes and operations, define the class 
hierarchy and create a class diagram with Visual 
Studio. 
64
Exercises (2) 
2. Define class Human with first name and last name. 
Define new class Student which is derived from 
Human and has new field – grade. Define class Worker 
derived from Human with new field weekSalary and 
work-hours per day and method MoneyPerHour() 
that returns money earned by hour by the worker. 
Define the proper constructors and properties for this 
hierarchy. Initialize an array of 10 students and sort 
them by grade in ascending order. Initialize an array of 
10 workers and sort them by money per hour in 
descending order. 
65
Exercises (3) 3. Define abstract class Shape with only one virtual 
method CalculateSurface() and fields width and 
height. Define two new classes Triangle and 
Rectangle that implement the virtual method and 
return the surface of the figure (height*width for 
rectangle and height*width/2 for triangle). Define class 
Circle and suitable constructor so that on 
initialization height must be kept equal to width and 
implement the CalculateSurface() method. Write 
a program that tests the behavior of the 
CalculateSurface() method for different shapes 
(Circle, Rectangle, Triangle) stored in an array. 
66
Exercises (4) 
4. Create a hierarchy Dog, Frog, Cat, Kitten, Tomcat 
and define suitable constructors and methods 
according to the following rules: all of this are Animals. 
Kittens and tomcats are cats. All animals are described 
by age, name and sex. Kittens can be only female and 
tomcats can be only male. Each animal produce a 
sound. Create arrays of different kinds of animals and 
calculate the average age of each kind of animal using 
static methods. Create static method in the animal 
class that identifies the animal by its sound. 
67
Exercises (5) 
5. A bank holds different types of accounts for its 
customers: deposit accounts, loan accounts and 
mortgage accounts. Customers could be 
individuals or companies. 
All accounts have customer, balance and interest 
rate (monthly based). Deposit accounts are 
allowed to deposit and with draw money. Loan 
and mortgage accounts can only deposit money. 
68
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. 
69
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. 
70

More Related Content

What's hot

Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java Hitesh-Java
 
GUI Programming using NetBeans (1).pptx
GUI Programming using NetBeans (1).pptxGUI Programming using NetBeans (1).pptx
GUI Programming using NetBeans (1).pptxSumalee Sonamthiang
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NETRajkumarsoy
 
Object Oriented Analysis Design using UML
Object Oriented Analysis Design using UMLObject Oriented Analysis Design using UML
Object Oriented Analysis Design using UMLAjit Nayak
 
UBIQUITOUS COMPUTING - Mary M
UBIQUITOUS COMPUTING - Mary MUBIQUITOUS COMPUTING - Mary M
UBIQUITOUS COMPUTING - Mary MMary Margarat
 
Windows form application - C# Training
Windows form application - C# Training Windows form application - C# Training
Windows form application - C# Training Moutasm Tamimi
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introductionBhagath Gopinath
 
Graphical User Interface (Gui)
Graphical User Interface (Gui)Graphical User Interface (Gui)
Graphical User Interface (Gui)Bilal Amjad
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual BasicSangeetha Sg
 
Human computer interaction
Human computer interactionHuman computer interaction
Human computer interactionemaan waseem
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns pptAman Jain
 
Architecture of .net framework
Architecture of .net frameworkArchitecture of .net framework
Architecture of .net frameworkThen Murugeshwari
 
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)Beat Signer
 

What's hot (20)

Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
GUI Programming using NetBeans (1).pptx
GUI Programming using NetBeans (1).pptxGUI Programming using NetBeans (1).pptx
GUI Programming using NetBeans (1).pptx
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
Introduction to .net
Introduction to .netIntroduction to .net
Introduction to .net
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Object Oriented Analysis Design using UML
Object Oriented Analysis Design using UMLObject Oriented Analysis Design using UML
Object Oriented Analysis Design using UML
 
UBIQUITOUS COMPUTING - Mary M
UBIQUITOUS COMPUTING - Mary MUBIQUITOUS COMPUTING - Mary M
UBIQUITOUS COMPUTING - Mary M
 
Netbeans IDE & Platform
Netbeans IDE & PlatformNetbeans IDE & Platform
Netbeans IDE & Platform
 
Prototype Design Pattern
Prototype Design PatternPrototype Design Pattern
Prototype Design Pattern
 
Windows form application - C# Training
Windows form application - C# Training Windows form application - C# Training
Windows form application - C# Training
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introduction
 
Java
JavaJava
Java
 
Graphical User Interface (Gui)
Graphical User Interface (Gui)Graphical User Interface (Gui)
Graphical User Interface (Gui)
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual Basic
 
Human computer interaction
Human computer interactionHuman computer interaction
Human computer interaction
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
 
.Net Core
.Net Core.Net Core
.Net Core
 
Architecture of .net framework
Architecture of .net frameworkArchitecture of .net framework
Architecture of .net framework
 
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)
 

Viewers also liked

Python decorators
Python decoratorsPython decorators
Python decoratorsAlex Su
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsP3 InfoTech Solutions Pvt. Ltd.
 
Advanced Python Techniques: Decorators
Advanced Python Techniques: DecoratorsAdvanced Python Techniques: Decorators
Advanced Python Techniques: DecoratorsTomo Popovic
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesOXUS 20
 
Visualizing Relationships between Python objects - EuroPython 2008
Visualizing Relationships between Python objects - EuroPython 2008Visualizing Relationships between Python objects - EuroPython 2008
Visualizing Relationships between Python objects - EuroPython 2008Dinu Gherman
 
HT16 - DA361A - OOP med Python
HT16 - DA361A - OOP med PythonHT16 - DA361A - OOP med Python
HT16 - DA361A - OOP med PythonAnton Tibblin
 
Oop design principles
Oop design principlesOop design principles
Oop design principlesSayed Ahmed
 
Creative Language and Creative Process Across Disciplines: Music, Programming...
Creative Language and Creative Process Across Disciplines: Music, Programming...Creative Language and Creative Process Across Disciplines: Music, Programming...
Creative Language and Creative Process Across Disciplines: Music, Programming...jwettersten
 
Object Oriented Concept
Object Oriented ConceptObject Oriented Concept
Object Oriented ConceptD Nayanathara
 
Advance Database Management Systems -Object Oriented Principles In Database
Advance Database Management Systems -Object Oriented Principles In DatabaseAdvance Database Management Systems -Object Oriented Principles In Database
Advance Database Management Systems -Object Oriented Principles In DatabaseSonali Parab
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++Swarup Kumar Boro
 
Advanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsAdvanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsClint Edmonson
 
OOP paradigm, principles of good design and architecture of Java applications
OOP paradigm, principles of good design and architecture of Java applicationsOOP paradigm, principles of good design and architecture of Java applications
OOP paradigm, principles of good design and architecture of Java applicationsMikalai Alimenkou
 
Webium: Page Objects In Python (Eng)
Webium: Page Objects In Python (Eng)Webium: Page Objects In Python (Eng)
Webium: Page Objects In Python (Eng)Uladzimir Franskevich
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in PythonBen James
 

Viewers also liked (20)

Python decorators
Python decoratorsPython decorators
Python decorators
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
 
Advanced Python Techniques: Decorators
Advanced Python Techniques: DecoratorsAdvanced Python Techniques: Decorators
Advanced Python Techniques: Decorators
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
 
Visualizing Relationships between Python objects - EuroPython 2008
Visualizing Relationships between Python objects - EuroPython 2008Visualizing Relationships between Python objects - EuroPython 2008
Visualizing Relationships between Python objects - EuroPython 2008
 
HT16 - DA361A - OOP med Python
HT16 - DA361A - OOP med PythonHT16 - DA361A - OOP med Python
HT16 - DA361A - OOP med Python
 
Oop design principles
Oop design principlesOop design principles
Oop design principles
 
java Oops.ppt
java Oops.pptjava Oops.ppt
java Oops.ppt
 
Creative Language and Creative Process Across Disciplines: Music, Programming...
Creative Language and Creative Process Across Disciplines: Music, Programming...Creative Language and Creative Process Across Disciplines: Music, Programming...
Creative Language and Creative Process Across Disciplines: Music, Programming...
 
Chapter1 Introduction to OOP (Java)
Chapter1 Introduction to OOP (Java)Chapter1 Introduction to OOP (Java)
Chapter1 Introduction to OOP (Java)
 
Python Objects
Python ObjectsPython Objects
Python Objects
 
Object Oriented Concept
Object Oriented ConceptObject Oriented Concept
Object Oriented Concept
 
Advance Database Management Systems -Object Oriented Principles In Database
Advance Database Management Systems -Object Oriented Principles In DatabaseAdvance Database Management Systems -Object Oriented Principles In Database
Advance Database Management Systems -Object Oriented Principles In Database
 
Advanced Python : Decorators
Advanced Python : DecoratorsAdvanced Python : Decorators
Advanced Python : Decorators
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
Advanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsAdvanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, Idioms
 
OOP paradigm, principles of good design and architecture of Java applications
OOP paradigm, principles of good design and architecture of Java applicationsOOP paradigm, principles of good design and architecture of Java applications
OOP paradigm, principles of good design and architecture of Java applications
 
Webium: Page Objects In Python (Eng)
Webium: Page Objects In Python (Eng)Webium: Page Objects In Python (Eng)
Webium: Page Objects In Python (Eng)
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
 
Ppt on java basics
Ppt on java basicsPpt on java basics
Ppt on java basics
 

Similar to Object oriented programming Fundamental Concepts

20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principlesmaznabili
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental PrinciplesIntro C# Book
 
Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#Svetlin Nakov
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppthenokmetaferia1
 
Advanced c#
Advanced c#Advanced c#
Advanced c#saranuru
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentSuresh Mohta
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Getachew Ganfur
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming CourseDennis Chang
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoopVladislav Hadzhiyski
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.pptMikeAdva
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .NetGreg Sohl
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 

Similar to Object oriented programming Fundamental Concepts (20)

20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#
 
Inheritance
InheritanceInheritance
Inheritance
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
 
C++ classes
C++ classesC++ classes
C++ classes
 
Oops
OopsOops
Oops
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
C# program structure
C# program structureC# program structure
C# program structure
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
LectureNotes-02-DSA
LectureNotes-02-DSALectureNotes-02-DSA
LectureNotes-02-DSA
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop
 
Lecture 8 Library classes
Lecture 8 Library classesLecture 8 Library classes
Lecture 8 Library classes
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.ppt
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 

More from Bharat Kalia

PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts Bharat Kalia
 
Groupware Technology Project Report
Groupware Technology Project ReportGroupware Technology Project Report
Groupware Technology Project ReportBharat Kalia
 
Extending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific ComputingExtending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific ComputingBharat Kalia
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud ComputingBharat Kalia
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C BasicsBharat Kalia
 
OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia Bharat Kalia
 
Mingle box - Online Job seeking System
Mingle box - Online Job seeking SystemMingle box - Online Job seeking System
Mingle box - Online Job seeking SystemBharat Kalia
 
Project report of OCR Recognition
Project report of OCR RecognitionProject report of OCR Recognition
Project report of OCR RecognitionBharat Kalia
 
Introduction to C++
Introduction to C++ Introduction to C++
Introduction to C++ Bharat Kalia
 
Basic Programs of C++
Basic Programs of C++Basic Programs of C++
Basic Programs of C++Bharat Kalia
 

More from Bharat Kalia (10)

PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Groupware Technology Project Report
Groupware Technology Project ReportGroupware Technology Project Report
Groupware Technology Project Report
 
Extending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific ComputingExtending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific Computing
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud Computing
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
 
OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia
 
Mingle box - Online Job seeking System
Mingle box - Online Job seeking SystemMingle box - Online Job seeking System
Mingle box - Online Job seeking System
 
Project report of OCR Recognition
Project report of OCR RecognitionProject report of OCR Recognition
Project report of OCR Recognition
 
Introduction to C++
Introduction to C++ Introduction to C++
Introduction to C++
 
Basic Programs of C++
Basic Programs of C++Basic Programs of C++
Basic Programs of C++
 

Recently uploaded

4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 

Recently uploaded (20)

4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 

Object oriented programming Fundamental Concepts

  • 2. 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 2
  • 4. 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 4 public class Labyrinth { … } public interface IFigure { … }
  • 5. 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 5
  • 6. Types of Inheritance  Inheritance terminology derived class base class / inherits parent class class implements interface derived interface implements base interface 6
  • 7. 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) 7
  • 8. Inheritance – Example Person +Name: String +Address: String Derived class Derived class Employee +Company: String +Salary: double Base class Student +School: String 8
  • 9. Class Hierarchies  Inheritance leads to a hierarchy of classes and/or interfaces in an application: 9 Game MultiplePlayersGame BoardGame Chess Backgammon SinglePlayerGame Minesweeper Solitaire … …
  • 10. 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> 10
  • 11. 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 11 public class Shape {...} public class Circle : Shape {...} public Circle (int x, int y) : base(x) {...}
  • 12. Simple Inheritance Example public class Mammal { public int Age { get; set; } public Mammal(int age) { this.Age = age; } public void Sleep() { Console.WriteLine("Shhh! I'm sleeping!"); } } 12
  • 13. Simple Inheritance Example p(ub2l)ic class Dog : Mammal { public string Breed { get; set; } public Dog(int age, string breed) : base(age) { this.Breed = breed; } public void WagTail() { Console.WriteLine("Tail wagging..."); } } 13
  • 15. 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 15
  • 16. Inheritance and class Accessibility Creature { protected string Name { get; private set; } private void Talk() { Console.WriteLine("I am creature ..."); } protected void Walk() { Console.WriteLine("Walking ..."); } } class Mammal : Creature { // base.Talk() can be invoked here // this.Name can be read but cannot be modified here } 16
  • 17. 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, "Labrador"); Console.WriteLine(joe.Breed); // joe.Walk() is protected and can not be invoked // joe.Talk() is private and can not be invoked // joe.Name = "Rex"; // Name cannot be accessed here // joe.Breed = "Shih Tzu"; // Can't modify Breed } } 17
  • 19. Inheritance: Important Aspects  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 19
  • 20. 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 20
  • 22. Abstraction  Abstraction means ignoring irrelevant features, properties, or functions and emphasizing the relevant ones ... "Relevant" to what?  ... relevant to the given project (with an eye to future reuse in similar projects)  Abstraction = managing complexity 22
  • 23. 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 "name" but not "color of eyes"  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 23
  • 24. Abstraction in .NET  In .NET abstraction is achieved in several ways:  Abstract classes  Interfaces  Inheritance Control +click() ButtonBase +Color : long Button RadioButton CheckBox 24
  • 25. Abstraction in .NET – Example 25 System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.Control System.Windows.Forms.ButtonBase System.Windows.Forms.Button
  • 26. Interfaces in C#  An interface is a set of operations (methods) that given object can perform  Also called "contract" 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 26
  • 27. 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 27
  • 28. Abstract Data Types  Abstract Data Types (ADT) are data types defined by a set of operations (interface) «interface»  Example: IList<T> +Add(item : Object) +Remove(item : Object) +Clear() … LinkedList<T> List<T> 28
  • 29. 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 29
  • 30. UML Class Diagram – Example 30 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
  • 31. Class Diagrams in Visual Studio Live Demo
  • 33. 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 33
  • 34. 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; } 34
  • 35. 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 35
  • 36. 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 36
  • 38. 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 38
  • 39. 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 "specialized" later 39
  • 40. Virtual Methods  Virtual method is method that can be used in the same way on instances of base and derived classes but its implementation is different  A method is said to be a virtual when it is declared as virtual public virtual void CalculateSurface()  Methods that are declared as virtual in a base class can be overridden using the keyword override in the derived class 40
  • 41. 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 41
  • 42. 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 42
  • 43. 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 43
  • 44. Polymorphism – Example (2) 44 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();
  • 46. Class Hierarchies: Real World Example
  • 47. Real World Example: Calculator  Creating an application like the Windows Calculator  Typical scenario for applying the object-oriented approach 47
  • 48. 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. 48
  • 49. Real World Example: Calculator  So(m3e) 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 49
  • 50. 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 50
  • 51. Calculator Classes 51 TextBox «interface» IPaintable Paint() Control -location -size -text -bgColor -faceColor -font Container Form Calculator AbstractButton Button CheckBox RadioButton MainMenu MenuItem Panel
  • 53. 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 53
  • 54. Good and Bad Cohesion  Good: hard disk, cdrom, floppy  BAD: spaghetti code 54
  • 55. Strong Cohesion  Strong cohesion example  Class Math that has methods: Sin(), Cos(), Asin() Sqrt(), Pow(), Exp() Math.PI, Math.E 55 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);
  • 56. Bad Cohesion  Bad cohesion example  Class Magic that has these methods:  Another example: 56 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();
  • 57. 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 57
  • 58. 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? 58
  • 59. Loose Coupling – Example class Report { public bool LoadFromFile(string fileName) {…} public bool SaveToFile(string fileName) {…} } class Printer { public static int Print(Report report) {…} } class Program { static void Main() { Report myReport = new Report(); myReport.LoadFromFile("C:DailyReport.rep"); Printer.Print(myReport); } } 59
  • 60. 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); } } 60
  • 61. Spaghetti Code  Combination of bad cohesion and tight coupling: 61 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() {…} }
  • 62. 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 62
  • 63. Object-Oriented Programming Fundamental Concepts Questions? http://academy.telerik.com
  • 64. Exercises 1. We are given a school. In the school there are classes of students. Each class has a set of teachers. Each teacher teaches a set of disciplines. Students have name and unique class number. Classes have unique text identifier. Teachers have name. Disciplines have name, number of lectures and number of exercises. Both teachers and students are people. Your task is to identify the classes (in terms of OOP) and their attributes and operations, define the class hierarchy and create a class diagram with Visual Studio. 64
  • 65. Exercises (2) 2. Define class Human with first name and last name. Define new class Student which is derived from Human and has new field – grade. Define class Worker derived from Human with new field weekSalary and work-hours per day and method MoneyPerHour() that returns money earned by hour by the worker. Define the proper constructors and properties for this hierarchy. Initialize an array of 10 students and sort them by grade in ascending order. Initialize an array of 10 workers and sort them by money per hour in descending order. 65
  • 66. Exercises (3) 3. Define abstract class Shape with only one virtual method CalculateSurface() and fields width and height. Define two new classes Triangle and Rectangle that implement the virtual method and return the surface of the figure (height*width for rectangle and height*width/2 for triangle). Define class Circle and suitable constructor so that on initialization height must be kept equal to width and implement the CalculateSurface() method. Write a program that tests the behavior of the CalculateSurface() method for different shapes (Circle, Rectangle, Triangle) stored in an array. 66
  • 67. Exercises (4) 4. Create a hierarchy Dog, Frog, Cat, Kitten, Tomcat and define suitable constructors and methods according to the following rules: all of this are Animals. Kittens and tomcats are cats. All animals are described by age, name and sex. Kittens can be only female and tomcats can be only male. Each animal produce a sound. Create arrays of different kinds of animals and calculate the average age of each kind of animal using static methods. Create static method in the animal class that identifies the animal by its sound. 67
  • 68. Exercises (5) 5. A bank holds different types of accounts for its customers: deposit accounts, loan accounts and mortgage accounts. Customers could be individuals or companies. All accounts have customer, balance and interest rate (monthly based). Deposit accounts are allowed to deposit and with draw money. Loan and mortgage accounts can only deposit money. 68
  • 69. 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. 69
  • 70. 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. 70

Editor's Notes

  1. 1##
  2. 3##
  3. 7##
  4. 21##
  5. 32##
  6. 37##
  7. 45##
  8. 46##