SlideShare a Scribd company logo
1 of 72
Object-Oriented Programming 
Fundamental Concepts 
Svetlin Nakov 
Telerik Corporation 
www.telerik.com
Contents 
1. Fundamental Principles of OOP 
2. Inheritance 
3. Abstraction 
4. Encapsulation 
5. Polymorphism 
6. Cohesion and Coupling 
2
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 
4
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 
6 
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 
7
Types of Inheritance 
 Inheritance terminology 
derived class 
base class / 
inherits parent class 
class implements interface 
derived interface implements base interface 
8
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) 
9
Inheritance – Example 
Person 
+Name: String 
+Address: String 
Derived class Derived class 
Employee 
+Company: String 
+Salary: double 
Base class 
Student 
+School: String 
10
Class Hierarchies 
 Inheritance leads to a hierarchy of classes 
and/or interfaces in an application: 
11 
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> 
12
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 
13 
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!"); 
} 
} 
14
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("Tail wagging..."); 
} 
} 
15
Simple 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 
17
Inheritance and Accessibility 
class 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 
} 
18
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 
} 
} 
19
Inheritance and Accessibility 
Live Demo
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 
21
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 
22
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 
24
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 
25
Abstraction in .NET 
 In .NET abstraction is achieved in several 
ways: 
 Abstract classes 
 Interfaces 
 Inheritance 
Control 
+click() 
ButtonBase 
+Color : long 
Button RadioButton CheckBox 
26
Abstraction in .NET – Example 
27 
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 
28
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 
29
Abstract Data Types 
 Abstract Data Types (ADT) are data types 
defined by a set of operations (interface) 
 Example: 
«interface» 
IList<T> 
+Add(item : Object) 
+Remove(item : Object) 
+Clear() 
… 
LinkedList<T> 
List<T> 
30
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 
31
UML Class Diagram – Example 
32 
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 
35
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; } 
36
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 
37
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 
38
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 
40
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 
41
Virtual Methods 
 Virtual method is method that can be used in 
the same way on instances of base and derived 
classes but its implementation is different 
 A method is said to be a virtual when it is 
declared as virtual 
 Methods that are declared as virtual in a base 
class can be overridden using the keyword 
override in the derived class 
42 
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 
43
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 
44
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 
45
Polymorphism – Example (2) 
46 
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 
49
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. 
50
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 
51
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 
52
Calculator Classes 
53 
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 
55
Good and Bad Cohesion 
 Good: hard disk, cdrom, floppy 
 BAD: spaghetti code 
56
Strong Cohesion 
 Strong cohesion example 
 Class Math that has methods: 
Sin(), Cos(), Asin() 
Sqrt(), Pow(), Exp() 
Math.PI, Math.E 
57 
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: 
58 
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 
59
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? 
60
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); 
} 
} 
61
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); 
} 
} 
62
Spaghetti Code 
 Combination of bad cohesion and tight coupling: 
63 
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 
64
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. 
66
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. 
67
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. 
68
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. 
69
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. 
70
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. 
71
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. 
72

More Related Content

What's hot

Lecture 1 uml with java implementation
Lecture 1 uml with java implementationLecture 1 uml with java implementation
Lecture 1 uml with java implementationthe_wumberlog
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oopsHirra Sultan
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vineeta Garg
 
OOP Concepets and UML Class Diagrams
OOP Concepets and UML Class DiagramsOOP Concepets and UML Class Diagrams
OOP Concepets and UML Class DiagramsBhathiya Nuwan
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principlesdeonpmeyer
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and InterfaceHaris Bin Zahid
 
Object Oriented Programming using C++ Part II
Object Oriented Programming using C++ Part IIObject Oriented Programming using C++ Part II
Object Oriented Programming using C++ Part IIAjit Nayak
 
C# Summer course - Lecture 2
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2mohamedsamyali
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple Inheritanceadil raja
 
Object Oriented Concepts in Real Projects
Object Oriented Concepts in Real ProjectsObject Oriented Concepts in Real Projects
Object Oriented Concepts in Real ProjectsEPAM
 
Introduction to oop
Introduction to oop Introduction to oop
Introduction to oop Kumar
 
Inheritance
InheritanceInheritance
InheritanceTech_MX
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending ClassesNilesh Dalvi
 
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...Simplilearn
 

What's hot (20)

Lecture 1 uml with java implementation
Lecture 1 uml with java implementationLecture 1 uml with java implementation
Lecture 1 uml with java implementation
 
Object oriented programming With C#
Object oriented programming With C#Object oriented programming With C#
Object oriented programming With C#
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
OOP Concepets and UML Class Diagrams
OOP Concepets and UML Class DiagramsOOP Concepets and UML Class Diagrams
OOP Concepets and UML Class Diagrams
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
 
inheritance in C++
inheritance in C++inheritance in C++
inheritance in C++
 
Object Oriented Programming using C++ Part II
Object Oriented Programming using C++ Part IIObject Oriented Programming using C++ Part II
Object Oriented Programming using C++ Part II
 
Inheritance
InheritanceInheritance
Inheritance
 
C# Summer course - Lecture 2
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple Inheritance
 
Object Oriented Concepts in Real Projects
Object Oriented Concepts in Real ProjectsObject Oriented Concepts in Real Projects
Object Oriented Concepts in Real Projects
 
Introduction to oop
Introduction to oop Introduction to oop
Introduction to oop
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
 
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
 

Viewers also liked

Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming ConceptsMohamed Emam
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming ConceptsAbhigyan Singh Yadav
 
Characteristics of OOPS
Characteristics of OOPS Characteristics of OOPS
Characteristics of OOPS abhishek kumar
 
Advance Javascript for Coders
Advance Javascript for CodersAdvance Javascript for Coders
Advance Javascript for CodersPaddy Lock
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts246paa
 
OOPS features using Objective C
OOPS features using Objective COOPS features using Objective C
OOPS features using Objective CTiyasi Acharya
 
Object Oriented Paradigm
Object Oriented ParadigmObject Oriented Paradigm
Object Oriented ParadigmHüseyin Ergin
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programmingSachin Sharma
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01Adil Kakakhel
 
Principles of object oriented programming
Principles of object oriented programmingPrinciples of object oriented programming
Principles of object oriented programmingAmogh Kalyanshetti
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 

Viewers also liked (16)

Oops
OopsOops
Oops
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
OOP concepts
OOP conceptsOOP concepts
OOP concepts
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
concept of oops
concept of oopsconcept of oops
concept of oops
 
Characteristics of OOPS
Characteristics of OOPS Characteristics of OOPS
Characteristics of OOPS
 
Advance Javascript for Coders
Advance Javascript for CodersAdvance Javascript for Coders
Advance Javascript for Coders
 
Java Object Oriented Programming
Java Object Oriented Programming Java Object Oriented Programming
Java Object Oriented Programming
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
OOPS features using Objective C
OOPS features using Objective COOPS features using Objective C
OOPS features using Objective C
 
Object Oriented Paradigm
Object Oriented ParadigmObject Oriented Paradigm
Object Oriented Paradigm
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programming
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
 
Principles of object oriented programming
Principles of object oriented programmingPrinciples of object oriented programming
Principles of object oriented programming
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 

Similar to 20 Object-oriented programming principles

Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#Svetlin Nakov
 
Advanced c#
Advanced c#Advanced c#
Advanced c#saranuru
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppthenokmetaferia1
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ Dev Chauhan
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Getachew Ganfur
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming CourseDennis Chang
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoopVladislav Hadzhiyski
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .NetGreg Sohl
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.pptMikeAdva
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsITNet
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methodsfarhan amjad
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 
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
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)ssuser7f90ae
 

Similar to 20 Object-oriented programming principles (20)

Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
 
C++ classes
C++ classesC++ classes
C++ classes
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop
 
Inheritance
InheritanceInheritance
Inheritance
 
Oops
OopsOops
Oops
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.ppt
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objects
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
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
 
Oops concept
Oops conceptOops concept
Oops concept
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 

More from maznabili

22 Methodology of problem solving
22 Methodology of problem solving22 Methodology of problem solving
22 Methodology of problem solvingmaznabili
 
21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii21 High-quality programming code construction part-ii
21 High-quality programming code construction part-iimaznabili
 
21 high-quality programming code construction part-i
21 high-quality programming code construction part-i21 high-quality programming code construction part-i
21 high-quality programming code construction part-imaznabili
 
19 Algorithms and complexity
19 Algorithms and complexity19 Algorithms and complexity
19 Algorithms and complexitymaznabili
 
18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and setsmaznabili
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphsmaznabili
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structuresmaznabili
 
15 Text files
15 Text files15 Text files
15 Text filesmaznabili
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classesmaznabili
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processingmaznabili
 
12 Exceptions handling
12 Exceptions handling12 Exceptions handling
12 Exceptions handlingmaznabili
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objectsmaznabili
 
10 Recursion
10 Recursion10 Recursion
10 Recursionmaznabili
 
08 Numeral systems
08 Numeral systems08 Numeral systems
08 Numeral systemsmaznabili
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statementsmaznabili
 
04 Console input output-
04 Console input output-04 Console input output-
04 Console input output-maznabili
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressionsmaznabili
 

More from maznabili (20)

22 Methodology of problem solving
22 Methodology of problem solving22 Methodology of problem solving
22 Methodology of problem solving
 
21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii
 
21 high-quality programming code construction part-i
21 high-quality programming code construction part-i21 high-quality programming code construction part-i
21 high-quality programming code construction part-i
 
19 Algorithms and complexity
19 Algorithms and complexity19 Algorithms and complexity
19 Algorithms and complexity
 
18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and sets
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
 
15 Text files
15 Text files15 Text files
15 Text files
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classes
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
 
12 Exceptions handling
12 Exceptions handling12 Exceptions handling
12 Exceptions handling
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
10 Recursion
10 Recursion10 Recursion
10 Recursion
 
09 Methods
09 Methods09 Methods
09 Methods
 
08 Numeral systems
08 Numeral systems08 Numeral systems
08 Numeral systems
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
06 Loops
06 Loops06 Loops
06 Loops
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statements
 
04 Console input output-
04 Console input output-04 Console input output-
04 Console input output-
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressions
 

Recently uploaded

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 

20 Object-oriented programming principles

  • 1. Object-Oriented Programming Fundamental Concepts Svetlin Nakov Telerik Corporation www.telerik.com
  • 2. Contents 1. Fundamental Principles of OOP 2. Inheritance 3. Abstraction 4. Encapsulation 5. Polymorphism 6. Cohesion and Coupling 2
  • 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 4
  • 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 6 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 7
  • 8. Types of Inheritance  Inheritance terminology derived class base class / inherits parent class class implements interface derived interface implements base interface 8
  • 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) 9
  • 10. Inheritance – Example Person +Name: String +Address: String Derived class Derived class Employee +Company: String +Salary: double Base class Student +School: String 10
  • 11. Class Hierarchies  Inheritance leads to a hierarchy of classes and/or interfaces in an application: 11 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> 12
  • 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 13 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("Shhh! I'm sleeping!"); } } 14
  • 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("Tail wagging..."); } } 15
  • 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 17
  • 18. Inheritance and Accessibility class 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 } 18
  • 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, "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 } } 19
  • 21. 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 21
  • 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 22
  • 24. 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 24
  • 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 "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 25
  • 26. Abstraction in .NET  In .NET abstraction is achieved in several ways:  Abstract classes  Interfaces  Inheritance Control +click() ButtonBase +Color : long Button RadioButton CheckBox 26
  • 27. Abstraction in .NET – Example 27 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 "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 28
  • 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 29
  • 30. Abstract Data Types  Abstract Data Types (ADT) are data types defined by a set of operations (interface)  Example: «interface» IList<T> +Add(item : Object) +Remove(item : Object) +Clear() … LinkedList<T> List<T> 30
  • 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 31
  • 32. UML Class Diagram – Example 32 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 35
  • 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; } 36
  • 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 37
  • 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 38
  • 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 40
  • 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 "specialized" later 41
  • 42. Virtual Methods  Virtual method is method that can be used in the same way on instances of base and derived classes but its implementation is different  A method is said to be a virtual when it is declared as virtual  Methods that are declared as virtual in a base class can be overridden using the keyword override in the derived class 42 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 43
  • 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 44
  • 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 45
  • 46. Polymorphism – Example (2) 46 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 49
  • 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. 50
  • 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 51
  • 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 52
  • 53. Calculator Classes 53 TextBox «interface» IPaintable Paint() Control -location -size -text -bgColor -faceColor -font 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 55
  • 56. Good and Bad Cohesion  Good: hard disk, cdrom, floppy  BAD: spaghetti code 56
  • 57. Strong Cohesion  Strong cohesion example  Class Math that has methods: Sin(), Cos(), Asin() Sqrt(), Pow(), Exp() Math.PI, Math.E 57 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: 58 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();
  • 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 59
  • 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? 60
  • 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("C:DailyReport.rep"); Printer.Print(myReport); } } 61
  • 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); } } 62
  • 63. Spaghetti Code  Combination of bad cohesion and tight coupling: 63 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 64
  • 65. Object-Oriented Programming Fundamental Concepts Questions? http://academy.telerik.com
  • 66. 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. 66
  • 67. 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. 67
  • 68. 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. 68
  • 69. 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. 69
  • 70. 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. 70
  • 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. 71
  • 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. 72

Editor's Notes

  1. 1##
  2. 3##
  3. 5##
  4. 9##
  5. 23##
  6. 34##
  7. 39##
  8. 47##
  9. 48##