object-oriented programming-with c#
TRANSCRIPT
Object-Oriented Object-Oriented Programming with C#Programming with C#
Classes, Constructors, Properties, Events, Static Classes, Constructors, Properties, Events, Static Members, Interfaces, Inheritance, PolymorphismMembers, Interfaces, Inheritance, Polymorphism
Doncho MinkovDoncho Minkov
Telerik School AcademyTelerik School Academyschoolacademy.telerik.comschoolacademy.telerik.com
Technical TrainerTechnical Trainerhttp://www.minkov.ithttp://www.minkov.it
Table of ContentsTable of Contents Defining ClassesDefining Classes Access ModifiersAccess Modifiers ConstructorsConstructors Fields, Constants and PropertiesFields, Constants and Properties Static MembersStatic Members StructuresStructures Delegates and EventsDelegates and Events InterfacesInterfaces InheritanceInheritance PolymorphismPolymorphism
OOP andOOP and .NET.NET InIn .NET.NET Framework the object-oriented approach Framework the object-oriented approach
has roots in the deepest architectural level has roots in the deepest architectural level AllAll .NET applications are object-oriented.NET applications are object-oriented AllAll .NET.NET languages are object-orientedlanguages are object-oriented The class concept from OOP hasThe class concept from OOP has two realizations:two realizations: Classes and structuresClasses and structures
There is no multiple inheritance in .NETThere is no multiple inheritance in .NET Classes can implement several interfaces at the Classes can implement several interfaces at the
same timesame time
Defining Classes Defining Classes
Classes in OOPClasses in OOP Classes model real-world objects and defineClasses model real-world objects and define Attributes Attributes (state, properties, fields)(state, properties, fields)
Behavior Behavior (methods, operations)(methods, operations) Classes describe structure of objectsClasses describe structure of objects Objects describe particular instance of a classObjects describe particular instance of a class
Properties hold information about the Properties hold information about the modeled object relevant to the problemmodeled object relevant to the problem
Operations implement object behaviorOperations implement object behavior
Classes in C#Classes in C# Classes in C# could have following members:Classes in C# could have following members: FieldsFields, , constantsconstants, , methodsmethods, , propertiesproperties, ,
indexersindexers, , eventsevents, , operatorsoperators, , constructorsconstructors, , destructorsdestructors
Inner typesInner types ( (inner classesinner classes, , structuresstructures, , interfacesinterfaces, , delegatesdelegates, ...), ...)
Members can have access modifiers (scope)Members can have access modifiers (scope) publicpublic, , privateprivate, , protectedprotected, , internalinternal
Members can beMembers can be staticstatic ( (commoncommon) ) or specific for a given objector specific for a given object
6
Simple Class DefinitionSimple Class Definition
public class Cat : Animal public class Cat : Animal {{ private string name;private string name; private string owner;private string owner; public Cat(string name, string owner)public Cat(string name, string owner) {{ this.name = name; this.name = name; this.owner = owner; this.owner = owner; }}
public string Namepublic string Name { { get { return name; }get { return name; } set { name = value; }set { name = value; } }}
FieldsFields
ConstructorConstructor
PropertyProperty
Begin of class definitionBegin of class definition
Inherited (base) Inherited (base) classclass
Simple Class Definition (2)Simple Class Definition (2)
public string Ownerpublic string Owner {{ get { return owner;}get { return owner;} set { owner = value; }set { owner = value; } }} public void SayMiau()public void SayMiau() {{ Console.WriteLine("Miauuuuuuu!");Console.WriteLine("Miauuuuuuu!"); }}} }
MethodMethod
End of End of class class
definitiondefinition
Class Definition and MembersClass Definition and Members Class definition consists of:Class definition consists of: Class declarationClass declaration
Inherited class or implemented interfacesInherited class or implemented interfaces
Fields (static or not)Fields (static or not)
Constructors (static or not)Constructors (static or not)
Properties (static or not)Properties (static or not)
Methods (static or not)Methods (static or not)
Events, inner types, etc.Events, inner types, etc.
Access ModifiersAccess ModifiersPublic, Private, Protected, InternalPublic, Private, Protected, Internal
Access ModifiersAccess Modifiers Class members can have access modifiersClass members can have access modifiers Used to restrict the classes able to access themUsed to restrict the classes able to access them
Supports the OOP principle "Supports the OOP principle "encapsulationencapsulation"" Class members can be:Class members can be: publicpublic – accessible from any class – accessible from any class
protectedprotected – accessible from the class itself and – accessible from the class itself and all its descendent classesall its descendent classes
privateprivate – accessible from the class itself only – accessible from the class itself only
internalinternal – accessible from the current – accessible from the current assembly (used by default)assembly (used by default)
Defining ClassesDefining ClassesExampleExample
Task: Define Class Task: Define Class DogDog Our task is to define a simple class that Our task is to define a simple class that
represents information about a dogrepresents information about a dog The dog should have name and breedThe dog should have name and breed
If there is no name or breed assigned If there is no name or breed assigned to the dog, it should be named "Balkan"to the dog, it should be named "Balkan"and its breed should be "Street excellent" and its breed should be "Street excellent"
It should be able to view and change the name It should be able to view and change the name and the breed of the dogand the breed of the dog
The dog should be able to barkThe dog should be able to bark
Defining Class Defining Class DogDog – Example – Example
public class Dogpublic class Dog{{ private string name;private string name; private string breed;private string breed;
public Dog()public Dog() { { this.name = "Balkan";this.name = "Balkan"; this.breed = "Street excellent";this.breed = "Street excellent"; }}
public Dog(string name, string breed)public Dog(string name, string breed) { { this.name = name;this.name = name; this.breed = breed; this.breed = breed; }} ////(example (example continues)continues)
Defining Class Defining Class DogDog – Example (2) – Example (2)
public string Namepublic string Name { { get { return name; }get { return name; } set { name = value; }set { name = value; } }} public string Breedpublic string Breed { { get { return breed; }get { return breed; } set { breed = value; }set { breed = value; } }}
public void SayBau()public void SayBau() {{ Console.WriteLine("{0} said: Bauuuuuu!", Console.WriteLine("{0} said: Bauuuuuu!", name);name); }}} }
Using Classes and ObjectsUsing Classes and Objects
Using ClassesUsing Classes How to use classes?How to use classes? Create a new instanceCreate a new instance
Access the properties of the classAccess the properties of the class
Invoke methodsInvoke methods
Handle eventsHandle events How to define classes?How to define classes? Create new class and define its membersCreate new class and define its members
Create new class using some other as base classCreate new class using some other as base class
How to Use Classes (Non-static)?How to Use Classes (Non-static)?
Create an instanceCreate an instance Initialize fieldsInitialize fields
Manipulate instanceManipulate instance Read / change propertiesRead / change properties
Invoke methodsInvoke methods
Handle eventsHandle events
Release occupied resourcesRelease occupied resources Done automatically in most casesDone automatically in most cases
Task: Dog MeetingTask: Dog Meeting Our task is as follows:Our task is as follows: Create 3 dogsCreate 3 dogs First should be named “Sharo”,First should be named “Sharo”, second – “Rex” second – “Rex”
and the last – left without nameand the last – left without name
Add all dogs in an arrayAdd all dogs in an array
Iterate through the array elements and ask Iterate through the array elements and ask each dog to barkeach dog to bark
Note:Note: Use the Use the DogDog class from the previous example! class from the previous example!
Dog Meeting – ExampleDog Meeting – Examplestatic void Main()static void Main(){{ Console.WriteLine("Enter first dog's name: ");Console.WriteLine("Enter first dog's name: "); dogName = Console.ReadLine();dogName = Console.ReadLine(); Console.WriteLine("Enter first dog's breed: ");Console.WriteLine("Enter first dog's breed: "); dogBreed = Console.ReadLine();dogBreed = Console.ReadLine();
// Using the Dog constructor to set name and breed// Using the Dog constructor to set name and breed Dog firstDog = new Dog(dogName, dogBreed);Dog firstDog = new Dog(dogName, dogBreed); Dog secondDog = new Dog();Dog secondDog = new Dog(); Console.WriteLine("Enter second dog's name: ");Console.WriteLine("Enter second dog's name: "); dogName = Console.ReadLine(); dogName = Console.ReadLine(); Console.WriteLine("Enter second dog's breed: ");Console.WriteLine("Enter second dog's breed: "); dogBreed = Console.ReadLine(); dogBreed = Console.ReadLine();
// Using properties to set name and breed// Using properties to set name and breed secondDog.Name = dogName;secondDog.Name = dogName; secondDog.Breed = dogBreed;secondDog.Breed = dogBreed;}}
ConstructorsConstructorsDefining and Using Class ConstructorsDefining and Using Class Constructors
What is Constructor?What is Constructor? Constructors are special methodsConstructors are special methods Invoked when creating a new instance of an Invoked when creating a new instance of an
objectobject
Used to initialize the fields of the instanceUsed to initialize the fields of the instance Constructors has the same name as the classConstructors has the same name as the class Have no return typeHave no return type
Can have parametersCan have parameters
Can be Can be privateprivate, , protectedprotected, , internalinternal, , publicpublic
Defining ConstructorsDefining Constructors
public class Pointpublic class Point{{ private int xCoord;private int xCoord; private int yCoord;private int yCoord;
// Simple default constructor// Simple default constructor public Point()public Point() { { xCoord = 0;xCoord = 0; yCoord = 0;yCoord = 0; }}
// More code ...// More code ...} }
Class Class PointPoint with parameterless constructor: with parameterless constructor:
Defining Constructors (2)Defining Constructors (2)public class Personpublic class Person{{ private string name;private string name; private int age;private int age; // Default constructor// Default constructor public Person()public Person() {{ name = "[no name]";name = "[no name]"; age = 0;age = 0; }} // Constructor with parameters// Constructor with parameters public Person(string name, int age)public Person(string name, int age) {{ this.name = name;this.name = name; this.age = age;this.age = age; }} // More code ...// More code ...} }
As rule As rule constructors should constructors should
initialize all own initialize all own class fields.class fields.
Constructors and InitializationConstructors and Initialization Pay attention when using inline initialization!Pay attention when using inline initialization!public class ClockAlarmpublic class ClockAlarm{{ private int hours = 9; // Inline initializationprivate int hours = 9; // Inline initialization private int minutes = 0; // Inline initializationprivate int minutes = 0; // Inline initialization // Default constructor// Default constructor public ClockAlarm()public ClockAlarm() { }{ } // Constructor with parameters// Constructor with parameters public ClockAlarm(int hours, int minutes)public ClockAlarm(int hours, int minutes) {{ this.hours = hours; // Invoked after the this.hours = hours; // Invoked after the
inline inline this.minutes = minutes; // initialization!this.minutes = minutes; // initialization! }} // More code ...// More code ...}}
Chaining Constructors CallsChaining Constructors Calls Reusing constructorsReusing constructors
public class Pointpublic class Point{{ private int xCoord;private int xCoord; private int yCoord;private int yCoord;
public Point() : this(0,0) // Reuse constructorpublic Point() : this(0,0) // Reuse constructor { { }}
public Point(int xCoord, int yCoord)public Point(int xCoord, int yCoord) {{ this.xCoord = xCoord;this.xCoord = xCoord; this.yCoord = yCoord;this.yCoord = yCoord; }}
// More code ...// More code ...} }
Fields, Constants and Fields, Constants and and Propertiesand Properties
FieldsFields FieldsFields contain data for the class instancecontain data for the class instance Can be arbitrary typeCan be arbitrary type Have given scopeHave given scope Can be declared with a specific valueCan be declared with a specific value
class Studentclass Student{{ private string firstName;private string firstName; private string lastName;private string lastName; private int course = 1;private int course = 1; private string speciality;private string speciality; protected Course[] coursesTaken;protected Course[] coursesTaken; private string remarks = "(no remarks)";private string remarks = "(no remarks)";}}
ConstantsConstants Constant fields are defined like fields, but:Constant fields are defined like fields, but: Defined withDefined with constconst
Must be initialized at their definitionMust be initialized at their definition
Their value can not be changed at runtimeTheir value can not be changed at runtime
public class MathConstantspublic class MathConstants{{ public const string PI_SYMBOL = "π";public const string PI_SYMBOL = "π"; public const double PI = 3.1415926535897932385;public const double PI = 3.1415926535897932385; public const double E = 2.7182818284590452354;public const double E = 2.7182818284590452354; public const double LN10 = 2.30258509299405;public const double LN10 = 2.30258509299405; public const double LN2 = 0.693147180559945;public const double LN2 = 0.693147180559945;}}
Read-Only FieldsRead-Only Fields Initialized at the definition or in the constructor Initialized at the definition or in the constructor Can not be modified furtherCan not be modified further
Defined with the keywordDefined with the keyword readonlyreadonly RepresentRepresent runtime constantsruntime constants
public class ReadOnlyDemopublic class ReadOnlyDemo{{ private readonly int size;private readonly int size; public ReadOnlyDemo(int Size)public ReadOnlyDemo(int Size) {{ size = Size; // can not be further modified!size = Size; // can not be further modified! }}}}
The Role of PropertiesThe Role of Properties
Expose object's data to the outside worldExpose object's data to the outside world Control how the data is manipulatedControl how the data is manipulated Properties can be:Properties can be: Read-onlyRead-only
Write-onlyWrite-only
Read and writeRead and write Give good level of abstractionGive good level of abstraction Make writing code easierMake writing code easier
Defining Properties in C#Defining Properties in C#
Properties should have:Properties should have: Access modifier (Access modifier (publicpublic, , protectedprotected, etc.), etc.)
Return typeReturn type
Unique nameUnique name
GetGet and / or and / or SetSet part part
Can contain code processing data in specific Can contain code processing data in specific wayway
Defining Properties – ExampleDefining Properties – Examplepublic class Pointpublic class Point{{ private int xCoord;private int xCoord; private int yCoord;private int yCoord;
public int XCoord public int XCoord {{ get { return xCoord; }get { return xCoord; } set { xCoord = value; }set { xCoord = value; } }}
public int YCoord public int YCoord {{ get { return yCoord; }get { return yCoord; } set { yCoord = value; }set { yCoord = value; } }}
// More code ...// More code ...} }
Dynamic PropertiesDynamic Properties Properties are not obligatory bound to a class Properties are not obligatory bound to a class
field – can be calculated dynamically:field – can be calculated dynamically:
public class Rectanglepublic class Rectangle{{ private float width;private float width; private float height;private float height;
// More code ...// More code ...
public float Areapublic float Area {{ getget {{ return width * height;return width * height; }} }}}}
Automatic PropertiesAutomatic Properties Properties could be defined without an Properties could be defined without an
underlying field behind themunderlying field behind them It is automatically created by the C# compilerIt is automatically created by the C# compiler
35
class UserProfileclass UserProfile{{ public int UserId { get; set; }public int UserId { get; set; } public string FirstName { get; set; }public string FirstName { get; set; } public string LastName { get; set; }public string LastName { get; set; }}}……UserProfile profile = new UserProfile() {UserProfile profile = new UserProfile() { FirstName = "Steve",FirstName = "Steve", LastName = "Balmer",LastName = "Balmer", UserId = 91112 };UserId = 91112 };
Static MembersStatic MembersStatic vs. Instance MembersStatic vs. Instance Members
Static MembersStatic Members Static members are associated with a type Static members are associated with a type
rather than with an instancerather than with an instance Defined with the modifier Defined with the modifier staticstatic
Static can be used forStatic can be used for FieldsFields
PropertiesProperties
MethodsMethods
EventsEvents
ConstructorsConstructors
Static vs. Non-StaticStatic vs. Non-Static StaticStatic: : Associated with a type, not with an instanceAssociated with a type, not with an instance
Non-StaticNon-Static: : The opposite, associated with an instanceThe opposite, associated with an instance
StaticStatic: : Initialized just before the type is used for the Initialized just before the type is used for the
first timefirst time Non-StaticNon-Static:: Initialized when the constructor is calledInitialized when the constructor is called
Static Members – ExampleStatic Members – Examplepublic class SqrtPrecalculatedpublic class SqrtPrecalculated{{ public const int MAX_VALUE = 10000;public const int MAX_VALUE = 10000;
// Static field // Static field private static int[] sqrtValues; private static int[] sqrtValues;
// Static constructor // Static constructor private static SqrtPrecalculated()private static SqrtPrecalculated() {{ sqrtValues = new int[MAX_VALUE + 1];sqrtValues = new int[MAX_VALUE + 1]; for (int i = 0; i < sqrtValues.Length; i++)for (int i = 0; i < sqrtValues.Length; i++) {{ sqrtValues[i] = (int)Math.Sqrt(i);sqrtValues[i] = (int)Math.Sqrt(i); }} }}
////(example continues)(example continues)
Static Members – Example (2)Static Members – Example (2)
// Static method // Static method public static int GetSqrt(int value)public static int GetSqrt(int value) {{ return sqrtValues[value];return sqrtValues[value]; }}
// The Main() method is always static// The Main() method is always static static void Main()static void Main() {{ Console.WriteLine(GetSqrt(254));Console.WriteLine(GetSqrt(254)); } } }}
StructuresStructures
StructuresStructures Structures represent a combination of fields Structures represent a combination of fields
with datawith data Look like the classes, but are value typesLook like the classes, but are value types
Their content is stored in the stackTheir content is stored in the stack
Transmitted by valueTransmitted by value
Destroyed when go out of scopeDestroyed when go out of scope However classes are reference type and are However classes are reference type and are
placed in the dynamic memory (heap)placed in the dynamic memory (heap) Their creation and destruction is slowerTheir creation and destruction is slower
StructuresStructures – – ExampleExample struct Pointstruct Point{{ public int X, Y;public int X, Y;}}
struct Colorstruct Color{{ public byte redValue;public byte redValue; public byte greenValue;public byte greenValue; public byte blueValue;public byte blueValue;}}
struct Squarestruct Square{{ public Point location;public Point location; public int size;public int size; public Color borderColor;public Color borderColor; public Color surfaceColor;public Color surfaceColor;}}
When to Use Structures?When to Use Structures? Use structuresUse structures To make your type behave as a primitive typeTo make your type behave as a primitive type
If you create many instances and after that you If you create many instances and after that you free themfree them – – e.g. in a cyclee.g. in a cycle
Do not use structuresDo not use structures When you often transmit your instances as When you often transmit your instances as
method parametersmethod parameters
If you use collections without genericsIf you use collections without generics ( (too too much boxingmuch boxing / / unboxing!)unboxing!)
Delegates and EventsDelegates and Events
What are Delegates?What are Delegates?
Delegates are reference typesDelegates are reference types Describe the signature of a given methodDescribe the signature of a given method Number and types of the parametersNumber and types of the parameters
The return typeThe return type Their "values" are methodsTheir "values" are methods These methods correspond to the signature of These methods correspond to the signature of
the delegatethe delegate
What are Delegates? (2)What are Delegates? (2)
Delegates are roughly similar to functionDelegates are roughly similar to function pointers inpointers in CC andand C++C++ Contain a strongly-typed pointer (reference) to Contain a strongly-typed pointer (reference) to
a methoda method They can point to both static or instance They can point to both static or instance
methodsmethods Used to perform callbacksUsed to perform callbacks
Delegates – ExampleDelegates – Example// Declaration of a delegate// Declaration of a delegatepublic delegate void SimpleDelegate(string param);public delegate void SimpleDelegate(string param);
public class TestDelegatepublic class TestDelegate{{ public static void TestFunction(string param)public static void TestFunction(string param) {{ Console.WriteLine("I was called by a delegate.");Console.WriteLine("I was called by a delegate."); Console.WriteLine("I got parameter {0}.", param);Console.WriteLine("I got parameter {0}.", param); }} public static void Main()public static void Main() {{ // Instantiation of а delegate// Instantiation of а delegate SimpleDelegate simpleDelegate =SimpleDelegate simpleDelegate = new SimpleDelegate(TestFunction);new SimpleDelegate(TestFunction); // Invocation of the method, pointed by a // Invocation of the method, pointed by a
delegatedelegate simpleDelegate("test");simpleDelegate("test"); }}}}
Anonymous MethodsAnonymous Methods
We are sometimes forced to create a class or a We are sometimes forced to create a class or a method just for the sake of using a delegatemethod just for the sake of using a delegate The code involved is often relatively The code involved is often relatively
short and simpleshort and simple Anonymous methodsAnonymous methods let you define an let you define an
nameless method called by a delegatenameless method called by a delegate Less codingLess coding
Improved code readabilityImproved code readability
Using Delegates: Standard WayUsing Delegates: Standard Way
class SomeClassclass SomeClass{{ delegate void SomeDelegate(string str);delegate void SomeDelegate(string str); public void InvokeMethod()public void InvokeMethod() {{ SomeDelegate dlg = new SomeDelegate dlg = new
SomeDelegate(SomeMethod);SomeDelegate(SomeMethod); dlg("Hello");dlg("Hello"); }}
void SomeMethod(string str)void SomeMethod(string str) {{ Console.WriteLine(str);Console.WriteLine(str); }}}}
Using Anonymous MethodsUsing Anonymous Methods The same thing can be accomplished by The same thing can be accomplished by
using an anonymous method:using an anonymous method:class SomeClassclass SomeClass{{ delegate void SomeDelegate(string str);delegate void SomeDelegate(string str); public void InvokeMethod()public void InvokeMethod() {{ SomeDelegate dlg = delegate(string str)SomeDelegate dlg = delegate(string str) {{ Console.WriteLine(str);Console.WriteLine(str); };}; dlg("Hello");dlg("Hello"); }}}}
EventsEvents In component-oriented programming the In component-oriented programming the
components send events to their owner to notify components send events to their owner to notify them when something happensthem when something happens E.g. when a button is pressed an event is raisedE.g. when a button is pressed an event is raised
The object which causes an event is called The object which causes an event is called event event sendersender
The object which receives an event is called The object which receives an event is called event receiverevent receiver
In order to be able to receive an event the event In order to be able to receive an event the event receivers must firstreceivers must first ""subscribe for the eventsubscribe for the event""
Events inEvents in .NET.NET In the component model ofIn the component model of .NET Framework .NET Framework
delegates and events provide mechanism for:delegates and events provide mechanism for: SubscriptionSubscription to an eventto an event
Sending an eventSending an event
Receiving an eventReceiving an event Events in C#Events in C# are special instances of delegates are special instances of delegates
declared by the C# keyworddeclared by the C# keyword eventevent Example (Example (Button.ClickButton.Click):):
public event EventHandler Click;public event EventHandler Click;
Events inEvents in .NET (2).NET (2) The C# compiler automatically defines the The C# compiler automatically defines the +=+=
and and -=-= operators for eventsoperators for events +=+= subscribe for an event subscribe for an event
-=-= unsubscribe for an eventunsubscribe for an event There are no other allowed operationsThere are no other allowed operations Example:Example:
Button button = new Button("OK");Button button = new Button("OK");button.Click += delegatebutton.Click += delegate{{ Console.WriteLine("Button clicked.");Console.WriteLine("Button clicked.");};};
Events vs. DelegatesEvents vs. Delegates EventsEvents are not the same as are not the same as member fields of member fields of
type delegatetype delegate
The event is processed by a delegateThe event is processed by a delegate Events can be members of an interface unlike Events can be members of an interface unlike
delegatesdelegates Calling of an event can only be doneCalling of an event can only be done in the in the
class it is defined inclass it is defined in By default the access to the events is By default the access to the events is
synchronized (thread-safe)synchronized (thread-safe)
public MyDelegate m;public MyDelegate m; public event MyDelegate m;public event MyDelegate m;≠
System.EventHandlerSystem.EventHandler Delegate Delegate Defines a referenceDefines a reference to ato a callbackcallback methodmethod, ,
whichwhich handles eventshandles events No additional information is sentNo additional information is sent
Used in many occasions internally inUsed in many occasions internally in .NET .NET E.g. in ASP.NET and Windows FormsE.g. in ASP.NET and Windows Forms
TheThe EventArgsEventArgs class is base class with no class is base class with no information about the eventinformation about the event Sometimes delegates derive from itSometimes delegates derive from it
public delegate void EventHandler(public delegate void EventHandler( Object sender, EventArgs e);Object sender, EventArgs e);
EventHandlerEventHandler – Example – Example
public class Buttonpublic class Button{{ public event EventHandler Click;public event EventHandler Click; public event EventHandler GotFocus;public event EventHandler GotFocus; public event EventHandler TextChanged;public event EventHandler TextChanged; ......}}public class ButtonTest public class ButtonTest {{ private static void Button_Click(object sender,private static void Button_Click(object sender, EventArgs eventArgs)EventArgs eventArgs) {{ Console.WriteLine("Call Button_Click() event");Console.WriteLine("Call Button_Click() event"); }} public static void Main()public static void Main() {{ Button button = new Button();Button button = new Button(); button.Click += Button_Click;button.Click += Button_Click; } } }}
Interfaces and Interfaces and Abstract ClassesAbstract Classes
InterfacesInterfaces Describe a group of Describe a group of methodsmethods (operations), (operations),
propertiesproperties and and eventsevents Can be implemented by given Can be implemented by given classclass or or structurestructure
Define only the methods’ prototypesDefine only the methods’ prototypes No concrete implementationNo concrete implementation Can be used to define Can be used to define abstractabstract data types data types Can not be instantiatedCan not be instantiated
Members do not have scope modifier Members do not have scope modifier and by default the scope is and by default the scope is publicpublic
Interfaces – ExampleInterfaces – Examplepublic interface IPersonpublic interface IPerson{{ string Name // property Namestring Name // property Name { get; set; }{ get; set; } DateTime DateOfBirth // property DateOfBirthDateTime DateOfBirth // property DateOfBirth { get; set; }{ get; set; } int Age // property Age (read-only)int Age // property Age (read-only) { get; }{ get; }}}
Interfaces – Example (2)Interfaces – Example (2)interface IShapeinterface IShape{{ void SetPosition(int x, int y);void SetPosition(int x, int y); int CalculateSurface();int CalculateSurface();}}
interface IMovableinterface IMovable{{ void Move(int deltaX, int deltaY);void Move(int deltaX, int deltaY);}}
interface IResizableinterface IResizable{{ void Resize(int weight);void Resize(int weight); void Resize(int weightX, int weightY);void Resize(int weightX, int weightY); void ResizeByX(int weightX);void ResizeByX(int weightX); void ResizeByY(int weightY);void ResizeByY(int weightY);}}
Interface ImplementationInterface Implementation Classes and structures can implement Classes and structures can implement
(support) one or many interfaces(support) one or many interfaces Interface realization must implement all its Interface realization must implement all its
methodsmethods If some methods do not have implementation If some methods do not have implementation
the the classclass or or structurestructure have to be declared have to be declared as an as an abstractabstract
Interface ImplementationInterface Implementation – –ExampleExample
class Rectangle : IShape, IMovableclass Rectangle : IShape, IMovable{{ private int x, y, width, height;private int x, y, width, height; public void SetPosition(int x, int y) // IShape public void SetPosition(int x, int y) // IShape {{ this.x = x;this.x = x; this.y = y;this.y = y; }} public int CalculateSurface() // IShapepublic int CalculateSurface() // IShape {{ return this.width * this.height;return this.width * this.height; }} public void Move(int deltaX, int deltaY) // IMovablepublic void Move(int deltaX, int deltaY) // IMovable {{ this.x += deltaX;this.x += deltaX; this.y += deltaY;this.y += deltaY; }}}}
Abstract ClassesAbstract Classes Abstract methodAbstract method is a method without is a method without
implementationimplementation Left empty to be implemented by descendant Left empty to be implemented by descendant
classesclasses When a class contains at least one abstract When a class contains at least one abstract
method, it is called method, it is called abstract classabstract class Mix between class and interfaceMix between class and interface
Inheritors are obligated toInheritors are obligated to implement their abstract methodsimplement their abstract methods
Can not be directly instantiatedCan not be directly instantiated
Abstract Class Abstract Class –– ExampleExample
abstract class MovableShape : IShape, IMovableabstract class MovableShape : IShape, IMovable{{ private int x, y;private int x, y; public void Move(int deltaX, int deltaY)public void Move(int deltaX, int deltaY) {{ this.x += deltaX;this.x += deltaX; this.y += deltaY;this.y += deltaY; }} public void SetPosition(int x, int y)public void SetPosition(int x, int y) {{ this.x = x;this.x = x; this.y = y;this.y = y; }} public abstract int CalculateSurface();public abstract int CalculateSurface();}}
Cohesion and CouplingCohesion and Coupling
CohesionCohesion CohesionCohesion describes how closely all the describes how closely all the
routines in a class or all the code in a routine routines in a class or all the code in a routine support a central purposesupport a central purpose Cohesion must be strongCohesion must be strong
Classes must contain strongly related Classes must contain strongly related functionality and aim for single purposefunctionality and aim for single purpose
Cohesion is a useful tool for managing Cohesion is a useful tool for managing complexity complexity
WWell-defined abstractionsell-defined abstractions keep cohesion strong keep cohesion strong
Good and Bad CohesionGood and Bad Cohesion Good cohesion: hard disk, CD-ROM, floppyGood cohesion: hard disk, CD-ROM, floppy
BAD: spaghetti codeBAD: spaghetti code
Strong CohesionStrong Cohesion Strong cohesion exampleStrong cohesion example Class Class MathMath that has methods: that has methods: Sin()Sin(), , Cos()Cos(), , Asin()Asin(), , Sqrt()Sqrt(), , Pow()Pow(), , Exp()Exp()
Math.PIMath.PI, , Math.EMath.E
double sideA = 40, sideB = 69;double sideA = 40, sideB = 69;double angleAB = Math.PI / 3;double angleAB = Math.PI / 3;
double sideC = double sideC = Math.Pow(sideA, 2) + Math.Pow(sideB, 2) Math.Pow(sideA, 2) + Math.Pow(sideB, 2)
- 2 * sideA * sideB * Math.Cos(angleAB);- 2 * sideA * sideB * Math.Cos(angleAB);
double sidesSqrtSum = Math.Sqrt(sideA) + double sidesSqrtSum = Math.Sqrt(sideA) + Math.Sqrt(sideB) + Math.Sqrt(sideC);Math.Sqrt(sideB) + Math.Sqrt(sideC);
Bad CohesionBad Cohesion Example of bad cohesionExample of bad cohesion Class Class MagicMagic that has all these methods: that has all these methods:
Another example:Another example:MagicClass.MakePizza("Fat Pepperoni");MagicClass.MakePizza("Fat Pepperoni");
MagicClass.WithdrawMoney("999e6");MagicClass.WithdrawMoney("999e6");
MagicClass.OpenDBConnection();MagicClass.OpenDBConnection();
public void PrintDocument(Document d);public void PrintDocument(Document d);
public void SendEmail(string recipient, string public void SendEmail(string recipient, string subject, string text);subject, string text);
public void CalculateDistanceBetweenPoints(int x1, public void CalculateDistanceBetweenPoints(int x1, int y1, int x2, int y2)int y1, int x2, int y2)
CouplingCoupling CouplingCoupling describes how tightly a class or describes how tightly a class or
routine is related to other classes or routine is related to other classes or routinesroutines Coupling must be kept looseCoupling must be kept loose Modules must depend little on each other Modules must depend little on each other
All classes and routines must have small, direct, All classes and routines must have small, direct, visible, and flexible relations to other classes visible, and flexible relations to other classes and routinesand routines
One module must be easily used by other One module must be easily used by other modulesmodules
Loose and Tight CouplingLoose and Tight Coupling
Loose Coupling:Loose Coupling: Easily replace old HDDEasily replace old HDD
Easily place this HDD to Easily place this HDD to another motherboardanother motherboard
Tight Coupling:Tight Coupling: Where is the video Where is the video
adapter?adapter?
Can you change the video Can you change the video controller?controller?
Loose Coupling – ExampleLoose Coupling – Exampleclass Reportclass Report{{ public bool LoadFromFile(string fileName) {…}public bool LoadFromFile(string fileName) {…} public bool SaveToFile(string fileName) {…}public bool SaveToFile(string fileName) {…}}}
class Printerclass Printer{{ public static int Print(Report report) {…}public static int Print(Report report) {…}}}
class LooseCouplingExampleclass LooseCouplingExample{ { static void Main()static void Main() {{ Report myReport = new Report(); Report myReport = new Report(); myReport.LoadFromFile("C:\\DailyReport.rep");myReport.LoadFromFile("C:\\DailyReport.rep"); Printer.Print(myReport);Printer.Print(myReport); }}}}
Tight Coupling – ExampleTight Coupling – Exampleclass MathParamsclass MathParams{{ public static double operand;public static double operand; public static double result;public static double result;}}class MathUtilclass MathUtil{{ public static void Sqrt()public static void Sqrt() {{ MathParams.result = MathParams.result =
CalcSqrt(MathParams.operand);CalcSqrt(MathParams.operand); }}} } class Exampleclass Example{{ static void Main()static void Main() {{ MathParams.operand = 64;MathParams.operand = 64; MathUtil.Sqrt();MathUtil.Sqrt(); Console.WriteLine(MathParams.result);Console.WriteLine(MathParams.result); }}}}
Spaghetti CodeSpaghetti Code Combination of bad cohesion and tight Combination of bad cohesion and tight
couplingcouplingclass Reportclass Report{{ public void Print() {…}public void Print() {…} public void InitPrinter() {…}public void InitPrinter() {…} public void LoadPrinterDriver(string fileName) {…}public void LoadPrinterDriver(string fileName) {…} public bool SaveReport(string fileName) {…}public bool SaveReport(string fileName) {…} public void SetPrinter(string printer) {…}public void SetPrinter(string printer) {…}}}
class Printerclass Printer{{ public void SetFileName() {…}public void SetFileName() {…} public static bool LoadReport() {…}public static bool LoadReport() {…} public static bool CheckReport() {…}public static bool CheckReport() {…}}}
InheritanceInheritance
InheritanceInheritance InheritanceInheritance is the ability of a class to implicitly is the ability of a class to implicitly
gain all members from another classgain all members from another class Inheritance is fundamental concept in OOPInheritance is fundamental concept in OOP
The class whose methods are inherited is The class whose methods are inherited is called called basebase (parent) class (parent) class
The class that gains new The class that gains new functionalityfunctionality is called is called derivedderived (child) class (child) class
Inheritance Inheritance establishes an establishes an is-ais-a relationship relationship between classes: A is Bbetween classes: A is B
Inheritance (2)Inheritance (2) All class members are inheritedAll class members are inherited FieldsFields, , methodsmethods, , propertiesproperties, …, …
InIn C#C# classes could be inheritedclasses could be inherited The structures in C#The structures in C# could not be inheritedcould not be inherited
Inheritance allows creating deep inheritance Inheritance allows creating deep inheritance hierarchieshierarchies
In In ..NET there is no multiple inheritance, NET there is no multiple inheritance, except when implementing interfacesexcept when implementing interfaces
How to Define How to Define InheritanceInheritance?? We must specify the name of the base class We must specify the name of the base class
after the name of the derived after the name of the derived
In the constructor of the derived class we use In the constructor of the derived class we use the keyword the keyword basebase to invoke the constructor of to invoke the constructor of the base classthe base class
public class Shapepublic class Shape{...}{...}public class Circle : Shapepublic class Circle : Shape{...}{...}
public Circle (int x, int y) : base(x)public Circle (int x, int y) : base(x){...}{...}
Inheritance Inheritance – – ExampleExamplepublic class Mammalpublic class Mammal{{ private int age;private int age;
public Mammal(int age)public Mammal(int age) {{ this.age = age;this.age = age; }}
public int Agepublic int Age {{ get { return age; }get { return age; } set { age = value; }set { age = value; } }}
public void Sleep()public void Sleep() {{ Console.WriteLine("Shhh! I'm sleeping!");Console.WriteLine("Shhh! I'm sleeping!"); }}}}
Inheritance Inheritance – – ExampleExample (2) (2)public class Dog : Mammalpublic class Dog : Mammal{{ private string breed;private string breed;
public Dog(int age, string breed): base(age)public Dog(int age, string breed): base(age) {{ this.breed = breed;this.breed = breed; }}
public string Breedpublic string Breed {{ get { return breed; }get { return breed; } set { breed = value; }set { breed = value; } }}
public void WagTail()public void WagTail() {{ Console.WriteLine("Tail wagging...");Console.WriteLine("Tail wagging..."); }}}}
Inheritance Inheritance – – ExampleExample (3) (3)
static void Main()static void Main(){{ // Create 5 years old mammal// Create 5 years old mammal Mamal mamal = new Mamal(5);Mamal mamal = new Mamal(5); Console.WriteLine(mamal.Age);Console.WriteLine(mamal.Age); mamal.Sleep(); mamal.Sleep();
// Create a bulldog, 3 years old// Create a bulldog, 3 years old Dog dog = new Dog("Bulldog", 3);Dog dog = new Dog("Bulldog", 3); dog.Sleep();dog.Sleep(); dog.Age = 4;dog.Age = 4; Console.WriteLine("Age: {0}", dog.Age);Console.WriteLine("Age: {0}", dog.Age); Console.WriteLine("Breed: {0}", dog.Breed);Console.WriteLine("Breed: {0}", dog.Breed); dog.WagTail();dog.WagTail();}}
PolymorphismPolymorphism
PolymorphismPolymorphism PolymorphismPolymorphism is fundamental concept in is fundamental concept in
OOPOOP The ability to handle the objects of a specific The ability to handle the objects of a specific
class as instances of its parent class and to call class as instances of its parent class and to call abstract functionalityabstract functionality
Polymorphism allows creating hierarchies Polymorphism allows creating hierarchies with more valuable logical structurewith more valuable logical structure Allows invoking abstract functionality without Allows invoking abstract functionality without
caring how and where it is implementedcaring how and where it is implemented
Polymorphism (2)Polymorphism (2) Polymorphism Polymorphism is usually is usually implementedimplemented
through:through: Virtual methods (Virtual methods (virtualvirtual))
Abstract methodsAbstract methods ( (abstractabstract))
Methods from an interface Methods from an interface ((interfaceinterface)) InIn C# to override virtual method the keyword C# to override virtual method the keyword overrideoverride is used is used
C#C# allows hiding virtual methods in derived allows hiding virtual methods in derived classes by the keyword classes by the keyword newnew
Polymorphism Polymorphism – – ExampleExample class Person class Person {{ public virtual void PrintName() public virtual void PrintName() {{ Console.WriteLine("I am a person.");Console.WriteLine("I am a person."); }}}}
class Trainer : Personclass Trainer : Person{{ public override void PrintName() public override void PrintName() {{ Console.WriteLine("I am a trainer.");Console.WriteLine("I am a trainer."); }}}}
class Student : Personclass Student : Person{{ public override void PrintName() public override void PrintName() {{ Console.WriteLine("I am a student.");Console.WriteLine("I am a student."); }}}}
Polymorphism Polymorphism – – Example (2)Example (2)
static void Main()static void Main(){{ Person[] persons = Person[] persons = {{ new Person(),new Person(), new Trainer(),new Trainer(), new Student()new Student() };}; foreach (Person p in persons)foreach (Person p in persons) {{ Console.WriteLine(p); Console.WriteLine(p); } }
// I am a person.// I am a person. // I am a trainer.// I am a trainer. // I am a student.// I am a student.}}
Questions?
Object-Oriented Object-Oriented Programming with C#Programming with C#