.NET Objects –
Classes & Interfaces.
Principles of OOP
Table of contents
• Classes.
 Definition
 Usage
 Access modifiers
 Fields, Properties, Methods, Events, Constructors, Indexers
 this
 Partial classes
• Interfaces
 Definition – Class public interface
 Usage
• Principles of OOP
.NET Classes
• Classes model real-world objects and define
 Attributes (state, properties, fields)
 Behavior (methods, operations)
• Classes describe the structure of objects
 Objects describe particular instance of a class
• Properties hold information about the modeled object relevant to the
problem
• Operations implement object behavior
.NET Classes (1)
• Classes in C# can have members:
 Fields, constants, methods, properties, indexers, events, operators, constructors,
destructors, …
 Inner types (inner classes, structures, interfaces, delegates, ...)
• Members can have access modifiers (scope)
 public, private, protected, internal
• Members can be
 static (common) or specific for a given object
Simple Class Definition
public class Cat : Animal
{
private string name;
private string owner;
public Cat(string name, string owner)
{
this.name = name;
this.owner = owner;
}
public string Name
{
get { return this.name; }
set { this.name = value; }
}
Fields
Constructor
Property
Begin of class definition
Inherited (base) class
5
Simple Class Definition (2)
public string Owner
{
get { return this.owner; }
set { this.owner = value; }
}
public void SayMiau()
{
Console.WriteLine("Miauuuuuuu!");
}
}
Method
End of class definition
Class Definition and Members
• Class definition consists of:
 Class declaration
 Inherited class or implemented interfaces
 Fields (static or not)
 Constructors (static or not)
 Properties (static or not)
 Methods (static or not)
 Events, inner types, etc.
7
Fields
• Fields are data members defined inside a class
 Fields hold the internal object state
 Can be static or per instance
 Can be private / public / protected / …
8
class Dog
{
private string name;
private string breed;
private int age;
protected Color color;
}
Field
declaration
s
Constant Fields
• Constant fields are of two types:
 Compile-time constants – const
 Replaced by their value during the compilation
 Can contain only values, known at compile time
 Runtime constants – readonly
 Assigned once only at object creation
 Can contain values, calculated run time
9
class Math
{
public const float PI = 3.14159;
public readonly Color =
Color.FromRGBA(25, 33, 74, 128);
}
Access Modifiers
• Class members can have access modifiers
 Restrict the access to them from outer sources
 Supports the OOP principle "encapsulation"
• Class members can be:
 public – accessible from any class
 protected – accessible from the class itself and all its descendent classes
 private – accessible from the class itself only
 internal (default) – accessible from the current assembly, i.e. the current VS project
10
Access Modifiers Explained
11
protectedinternal
protected internalprivate
public
The 'this' Keyword
• The keyword this inside a method points to the current instance of the class
• Example:
12
class Dog
{
private string name;
public void PrintName()
{
Console.WriteLine(this.name);
// The same like Console.WriteLine(name);
}
}
Methods
• Methods are class members that execute some action (some code, some
algorithm)
 Could be static / per instance
 Could be public / private / protected / …
13
public class Point
{
private int xCoord;
private int yCoord;
public double CalcDistance(Point p)
{
return Math.Sqrt(
(p.xCoord - this.xCoord) * (p.xCoord - this.xCoord) +
(p.yCoord - this.yCoord) * (p.yCoord - this.yCoord));
}
}
Using Methods
• Invoking instance methods is done through the object (class instance):
14
class TestMethods
{
static void Main()
{
Point p1 = new Point(2, 3);
Point p2 = new Point(3, 4);
System.Console.WriteLine(p1.CalcDistance(p2));
}
}
The Role of Properties
• Properties expose object's data to the world
 Control how the data is manipulated
 Ensure the internal object state is correct
 E.g. price should always be kept positive
• Properties can be:
 Read-only
 Write-only (examples)
 Read and write
• Simplify the writing of code
15
Defining Properties
• Properties work as a pair of methods
 Getter and setter
• Properties should have:
 Access modifier (public, protected, etc.)
 Return type
 Unique name
 Get and / or Set part
 Can contain code processing data in specific way, e.g. apply validation
16
Defining Properties – Example
public class Point
{
private int xCoord;
private int yCoord;
public int XCoord
{
get { return this.xCoord; }
set { this.xCoord = value; }
}
public int YCoord
{
get { return this.yCoord; }
set { this.yCoord = value; }
}
// More code ...
}
17
Dynamic Properties
• Properties are not obligatory bound to a class field – can be calculated
dynamically:
public class Rectangle
{
private double width;
private double height;
// More code …
public double Area
{
get
{
return width * height;
}
}
}
18
Automatic Properties
• Properties could be defined without an underlying field behind them
 It is automatically created by the compiler
19
class UserProfile
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
…
UserProfile profile = new UserProfile() {
FirstName = "Steve",
LastName = "Balmer",
UserId = 91112
};
What is Constructor?
• Constructors are special methods
 Invoked at the time of creating a new instance of an object
 Used to initialize the fields of the instance
• Constructors has the same name as the class
 Have no return type
 Can have parameters
 Can be private, protected, internal, public
20
Defining Constructors
public class Point
{
private int xCoord;
private int yCoord;
// Simple parameterless constructor
public Point()
{
this.xCoord = 0;
this.yCoord = 0;
}
// More code …
}
 Class Point with parameterless constructor:
21
Defining Constructors (2)
public class Person
{
private string name;
private int age;
// Parameterless constructor
public Person()
{
this.name = null;
this.age = 0;
}
// Constructor with parameters
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
// More code …
}
As rule constructors should
initialize all own class fields.
22
Constructors and Initialization
Pay attention when using inline initialization!
public class AlarmClock
{
private int hours = 9; // Inline initialization
private int minutes = 0; // Inline initialization
// Parameterless constructor (intentionally left empty)
public AlarmClock()
{ }
// Constructor with parameters
public AlarmClock(int hours, int minutes)
{
this.hours = hours; // Invoked after the inline
this.minutes = minutes; // initialization!
}
// More code …
}
23
Chaining Constructors Calls
Reusing constructors (chaining)
public class Point
{
private int xCoord;
private int yCoord;
public Point() : this(0, 0) // Reuse the constructor
{
}
public Point(int xCoord, int yCoord)
{
this.xCoord = xCoord;
this.yCoord = yCoord;
}
// More code …
}
24
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
25
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
27
public class Labyrinth { public int Size { get; set; } }
public interface IFigure { void Draw(); }
Inheritance
• Inheritance allows child classes to inherit the characteristics of an existing
parent (base) 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
Types of Inheritance
• Inheritance terminology
derived class
base class /
parent classinherits
derived
interface
base interfaceextends
class interfaceimplements
29
• Inheritance has a lot of benefits
 Extensibility
 Reusability (code reuse)
 Provides abstraction
 Eliminates redundant code
• Use inheritance for buidling is-a relationships
 E.g. dog is-a animal (dogs are kind of animals)
• Don't use it to build has-a relationship
 E.g. dog has-a name (dog is not kind of name)
Inheritance – Benefits
30
Inheritance
• Inheritance implicitly gains all members from another class
 All fields, methods, properties, events, …
 Some members could be inaccessible (hidden)
• The class whose methods are inherited is called base (parent) class
• The class that gains new functionality is called derived (child) class
31
Inheritance – Example
32
Person
+Name: String
+Address: String
Employee
+Company: String
+Salary: double
Student
+School: String
Base class
Derived classDerived class
Class Hierarchies
Inheritance leads to a hierarchies of classes and / or interfaces in an
application:
33
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>
34
How to Define Inheritance?
Specify the name of the base class after the name of the derived (with colon)
Use the keyword base to invoke the parent constructor
35
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!");
}
}
36
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...");
}
}
37
Simple Inheritance
Live Demo
Access 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
39
Inheritance and Accessibility
class Creature {
protected string Name { get; private set; }
protected void Walk()
{
Console.WriteLine("Walking ...");
}
private void Talk()
{
Console.WriteLine("I am creature ...");
}
}
class Mammal : Creature
{
// base.Walk() can be invoked here
// base.Talk() cannot be invoked here
// this.Name can be read but cannot be modified here
}
40
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
}
}
41
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
• Static members are also inherited
• 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
43
Inheritance: Important Features
• When a derived class extends its base class
 It can freely add new members
 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.ToString() is virtual method
44
Abstraction
• Abstraction means ignoring irrelevant features, properties, or functions and
emphasizing the relevant ones ...
• ... relevant to the given project
 With an eye to future reuse in similar projects
• Abstraction helps managing complexity
45
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
46
• In .NET object-oriented programming abstraction is achieved in several
ways:
 Abstract classes
 Interfaces
 Inheritance
+Color : long
ButtonBase
+click()
Control
Button RadioButton CheckBox
Abstraction in .NET
47
Abstraction in .NET – Example
48
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ButtonBase
System.Windows.Forms.Button
Interfaces
• An interface defines a set of operations (methods) that given object should
perform
 Also called "contract" for providing a set of operations
 Defines abstract behavior
• Interfaces provide abstractions
 You invoke the abstract actions
 Without worrying how it is internally implemented
49
Interfaces (2)
• Interfaces describe a prototype of group of methods (operations), properties
and events
 Can be implemented by a given class or structure
 Define only the prototypes of the operations
 No concrete implementation is provided
 Can be used to define abstract data types
 Can be inherited (extended) by other interfaces
 Can not be instantiated
50
Interfaces – Example
51
public interface IShape
{
void SetPosition(int x, int y);
int CalculateSurface();
}
public interface IMovable
{
void Move(int deltaX, int deltaY);
}
public interface IResizable
{
void Resize(int weight);
void Resize(int weightX, int weightY);
void ResizeByX(int weightX);
void ResizeByY(int weightY);
}
Interfaces – Example (2)
52
public interface IPerson
{
DateTime DateOfBirth // Property DateOfBirth
{
get;
set;
}
int Age // Property Age (read-only)
{
get;
}
void Print(); // Method for printing
}
Interface Implementation
Classes and structures can implement (support) one or several interfaces
Implementer classes must implement all interface methods
Or should be declared abstract
53
class Rectangle : IShape
{
public void SetPosition(int x, int y) { … }
public int CalculateSurface() { … }
}
Interface Implementation (2)
54
class Rectangle : IShape, IMovable
{
private int x, y, width, height;
public void SetPosition(int x, int y) // IShape
{
this.x = x;
this.y = y;
}
public int CalculateSurface() // IShape
{
return this.width * this.height;
}
public void Move(int deltaX, int deltaY) // IMovable
{
this.x += deltaX;
this.y += deltaY;
}
}
Interfaces and
Implementation
Live Demo
Abstract Classes
• 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 directly
• Child classes should implement all abstract methods or be declared as
abstract too
56
Abstract Classes (2)
• Abstract methods are empty methods without implementation
 The implementation is intentionally left
for the descendent classes
• When a class contains at least one abstract method, it is called abstract class
• Abstract classes model abstract concepts
 E.g. person, object, item, movable object
57
Abstract Class – Example
58
abstract class MovableShape : IShape, IMovable
{
private int x, y;
public void Move(int deltaX, int deltaY)
{
this.x += deltaX;
this.y += deltaY;
}
public void SetPosition(int x, int y)
{
this.x = x;
this.y = y;
}
public abstract int CalculateSurface();
}
Interfaces vs. Abstract Classes
• C# interfaces are like abstract classes, but in contrast interfaces:
 Can not contain methods with implementation
 All interface methods are abstract
 Members do not have scope modifiers
 Their scope is assumed public
 But this is not specified explicitly
 Can not define fields, constants, inner types and constructors
59
Abstract Classes – Example
60
public abstract class Animal : IComparable<Animal>
{
// Abstract methods
public abstract string GetName();
public abstract int Speed { get; }
// Non-abstract method
public override string ToString()
{
return "I am " + this.GetName();
}
// Interface method
public int CompareTo(Animal other)
{
return this.Speed.CompareTo(other.Speed);
}
}
Abstract Classes – Example (2)
61
public class Turtle : Animal
{
public override int Speed { get { return 1; } }
public override string GetName()
{ return "turtle"; }
}
public class Cheetah : Animal
{
public override int Speed { get { return 100; } }
public override string GetName()
{ return "cheetah"; }
}
Abstract Classes
Live Demo
Abstract Data Types
• Abstract Data Types (ADT) are data types defined by a set of operations
(interface)
• Example: IList<T> in .NET Framework
LinkedList<T>
+Add(item : Object)
+Remove(item : Object)
+Clear()
…
«interface»
IList<T>
List<T>
63
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
64
UML Class Diagram – Example
65
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
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
67
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; }
68
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
69
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
70
Encapsulation
Live Demo
Homework
Problem 1. School classes
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
a name and unique class number. Classes have unique text identifier.
Teachers have a name. Disciplines have a name, number of lectures and
number of exercises. Both teachers and students are people. Students, classes,
teachers and disciplines could have optional comments (free text block).
Your task is to identify the classes (in terms of OOP) and their attributes and
operations, encapsulate their fields and define the class hierarchy.
Problem 2*. Students and workers
Define abstract class Human with a first name and a last name. Define a new
class Student which is derived from Humanand has a new field – grade.
Define class Worker derived from Human with a new
property WeekSalary and WorkHoursPerDay and a
method MoneyPerHour() that returns money earned per hour by the worker.
Define the proper constructors and properties for this hierarchy.
Initialize a list of 10 students and sort them by grade in ascending order (use
LINQ or OrderBy() extension method).
Initialize a list of 10 workers and sort them by money per hour in descending
order.
Merge the lists and sort them by first name and last name.
Problem 3. Animal hierarchy
Create a hierarchy Dog, Frog, Cat, Kitten, Tomcat and define useful
constructors and methods. Dogs, frogs and cats are Animals. All animals can
produce sound (specified by the ISound interface). 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 produces a specific sound.
Create arrays of different kinds of animals and calculate the average age of
each kind of animal using a static method (you may use LINQ).
Questions?
Thank you
Vladislav Hadzhiyski
Email: Vladislav.Hadzhiyski@gmail.com

03 classes interfaces_principlesofoop

  • 1.
    .NET Objects – Classes& Interfaces. Principles of OOP
  • 2.
    Table of contents •Classes.  Definition  Usage  Access modifiers  Fields, Properties, Methods, Events, Constructors, Indexers  this  Partial classes • Interfaces  Definition – Class public interface  Usage • Principles of OOP
  • 3.
    .NET Classes • Classesmodel real-world objects and define  Attributes (state, properties, fields)  Behavior (methods, operations) • Classes describe the structure of objects  Objects describe particular instance of a class • Properties hold information about the modeled object relevant to the problem • Operations implement object behavior
  • 4.
    .NET Classes (1) •Classes in C# can have members:  Fields, constants, methods, properties, indexers, events, operators, constructors, destructors, …  Inner types (inner classes, structures, interfaces, delegates, ...) • Members can have access modifiers (scope)  public, private, protected, internal • Members can be  static (common) or specific for a given object
  • 5.
    Simple Class Definition publicclass Cat : Animal { private string name; private string owner; public Cat(string name, string owner) { this.name = name; this.owner = owner; } public string Name { get { return this.name; } set { this.name = value; } } Fields Constructor Property Begin of class definition Inherited (base) class 5
  • 6.
    Simple Class Definition(2) public string Owner { get { return this.owner; } set { this.owner = value; } } public void SayMiau() { Console.WriteLine("Miauuuuuuu!"); } } Method End of class definition
  • 7.
    Class Definition andMembers • Class definition consists of:  Class declaration  Inherited class or implemented interfaces  Fields (static or not)  Constructors (static or not)  Properties (static or not)  Methods (static or not)  Events, inner types, etc. 7
  • 8.
    Fields • Fields aredata members defined inside a class  Fields hold the internal object state  Can be static or per instance  Can be private / public / protected / … 8 class Dog { private string name; private string breed; private int age; protected Color color; } Field declaration s
  • 9.
    Constant Fields • Constantfields are of two types:  Compile-time constants – const  Replaced by their value during the compilation  Can contain only values, known at compile time  Runtime constants – readonly  Assigned once only at object creation  Can contain values, calculated run time 9 class Math { public const float PI = 3.14159; public readonly Color = Color.FromRGBA(25, 33, 74, 128); }
  • 10.
    Access Modifiers • Classmembers can have access modifiers  Restrict the access to them from outer sources  Supports the OOP principle "encapsulation" • Class members can be:  public – accessible from any class  protected – accessible from the class itself and all its descendent classes  private – accessible from the class itself only  internal (default) – accessible from the current assembly, i.e. the current VS project 10
  • 11.
  • 12.
    The 'this' Keyword •The keyword this inside a method points to the current instance of the class • Example: 12 class Dog { private string name; public void PrintName() { Console.WriteLine(this.name); // The same like Console.WriteLine(name); } }
  • 13.
    Methods • Methods areclass members that execute some action (some code, some algorithm)  Could be static / per instance  Could be public / private / protected / … 13 public class Point { private int xCoord; private int yCoord; public double CalcDistance(Point p) { return Math.Sqrt( (p.xCoord - this.xCoord) * (p.xCoord - this.xCoord) + (p.yCoord - this.yCoord) * (p.yCoord - this.yCoord)); } }
  • 14.
    Using Methods • Invokinginstance methods is done through the object (class instance): 14 class TestMethods { static void Main() { Point p1 = new Point(2, 3); Point p2 = new Point(3, 4); System.Console.WriteLine(p1.CalcDistance(p2)); } }
  • 15.
    The Role ofProperties • Properties expose object's data to the world  Control how the data is manipulated  Ensure the internal object state is correct  E.g. price should always be kept positive • Properties can be:  Read-only  Write-only (examples)  Read and write • Simplify the writing of code 15
  • 16.
    Defining Properties • Propertieswork as a pair of methods  Getter and setter • Properties should have:  Access modifier (public, protected, etc.)  Return type  Unique name  Get and / or Set part  Can contain code processing data in specific way, e.g. apply validation 16
  • 17.
    Defining Properties –Example public class Point { private int xCoord; private int yCoord; public int XCoord { get { return this.xCoord; } set { this.xCoord = value; } } public int YCoord { get { return this.yCoord; } set { this.yCoord = value; } } // More code ... } 17
  • 18.
    Dynamic Properties • Propertiesare not obligatory bound to a class field – can be calculated dynamically: public class Rectangle { private double width; private double height; // More code … public double Area { get { return width * height; } } } 18
  • 19.
    Automatic Properties • Propertiescould be defined without an underlying field behind them  It is automatically created by the compiler 19 class UserProfile { public int UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } … UserProfile profile = new UserProfile() { FirstName = "Steve", LastName = "Balmer", UserId = 91112 };
  • 20.
    What is Constructor? •Constructors are special methods  Invoked at the time of creating a new instance of an object  Used to initialize the fields of the instance • Constructors has the same name as the class  Have no return type  Can have parameters  Can be private, protected, internal, public 20
  • 21.
    Defining Constructors public classPoint { private int xCoord; private int yCoord; // Simple parameterless constructor public Point() { this.xCoord = 0; this.yCoord = 0; } // More code … }  Class Point with parameterless constructor: 21
  • 22.
    Defining Constructors (2) publicclass Person { private string name; private int age; // Parameterless constructor public Person() { this.name = null; this.age = 0; } // Constructor with parameters public Person(string name, int age) { this.name = name; this.age = age; } // More code … } As rule constructors should initialize all own class fields. 22
  • 23.
    Constructors and Initialization Payattention when using inline initialization! public class AlarmClock { private int hours = 9; // Inline initialization private int minutes = 0; // Inline initialization // Parameterless constructor (intentionally left empty) public AlarmClock() { } // Constructor with parameters public AlarmClock(int hours, int minutes) { this.hours = hours; // Invoked after the inline this.minutes = minutes; // initialization! } // More code … } 23
  • 24.
    Chaining Constructors Calls Reusingconstructors (chaining) public class Point { private int xCoord; private int yCoord; public Point() : this(0, 0) // Reuse the constructor { } public Point(int xCoord, int yCoord) { this.xCoord = xCoord; this.yCoord = yCoord; } // More code … } 24
  • 25.
    Fundamental Principles ofOOP • 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 25
  • 26.
  • 27.
    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 27 public class Labyrinth { public int Size { get; set; } } public interface IFigure { void Draw(); }
  • 28.
    Inheritance • Inheritance allowschild classes to inherit the characteristics of an existing parent (base) 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
  • 29.
    Types of Inheritance •Inheritance terminology derived class base class / parent classinherits derived interface base interfaceextends class interfaceimplements 29
  • 30.
    • Inheritance hasa lot of benefits  Extensibility  Reusability (code reuse)  Provides abstraction  Eliminates redundant code • Use inheritance for buidling is-a relationships  E.g. dog is-a animal (dogs are kind of animals) • Don't use it to build has-a relationship  E.g. dog has-a name (dog is not kind of name) Inheritance – Benefits 30
  • 31.
    Inheritance • Inheritance implicitlygains all members from another class  All fields, methods, properties, events, …  Some members could be inaccessible (hidden) • The class whose methods are inherited is called base (parent) class • The class that gains new functionality is called derived (child) class 31
  • 32.
    Inheritance – Example 32 Person +Name:String +Address: String Employee +Company: String +Salary: double Student +School: String Base class Derived classDerived class
  • 33.
    Class Hierarchies Inheritance leadsto a hierarchies of classes and / or interfaces in an application: 33 Game MultiplePlayersGame BoardGame Chess Backgammon SinglePlayerGame Minesweeper Solitaire … …
  • 34.
    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> 34
  • 35.
    How to DefineInheritance? Specify the name of the base class after the name of the derived (with colon) Use the keyword base to invoke the parent constructor 35 public class Shape { … } public class Circle : Shape { … } public Circle (int x, int y) : base(x) { … }
  • 36.
    Simple Inheritance Example publicclass Mammal { public int Age { get; set; } public Mammal(int age) { this.Age = age; } public void Sleep() { Console.WriteLine("Shhh! I'm sleeping!"); } } 36
  • 37.
    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..."); } } 37
  • 38.
  • 39.
    Access Levels Access modifiersin 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 39
  • 40.
    Inheritance and Accessibility classCreature { protected string Name { get; private set; } protected void Walk() { Console.WriteLine("Walking ..."); } private void Talk() { Console.WriteLine("I am creature ..."); } } class Mammal : Creature { // base.Walk() can be invoked here // base.Talk() cannot be invoked here // this.Name can be read but cannot be modified here } 40
  • 41.
    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 } } 41
  • 42.
  • 43.
    Inheritance: Important Aspects •Structures cannot be inherited • In C# there is no multiple inheritance  Only multiple interfaces can be implemented • Static members are also inherited • 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 43
  • 44.
    Inheritance: Important Features •When a derived class extends its base class  It can freely add new members  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.ToString() is virtual method 44
  • 45.
    Abstraction • Abstraction meansignoring irrelevant features, properties, or functions and emphasizing the relevant ones ... • ... relevant to the given project  With an eye to future reuse in similar projects • Abstraction helps managing complexity 45
  • 46.
    Abstraction (2) • Abstractionis 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 46
  • 47.
    • In .NETobject-oriented programming abstraction is achieved in several ways:  Abstract classes  Interfaces  Inheritance +Color : long ButtonBase +click() Control Button RadioButton CheckBox Abstraction in .NET 47
  • 48.
    Abstraction in .NET– Example 48 System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.Control System.Windows.Forms.ButtonBase System.Windows.Forms.Button
  • 49.
    Interfaces • An interfacedefines a set of operations (methods) that given object should perform  Also called "contract" for providing a set of operations  Defines abstract behavior • Interfaces provide abstractions  You invoke the abstract actions  Without worrying how it is internally implemented 49
  • 50.
    Interfaces (2) • Interfacesdescribe a prototype of group of methods (operations), properties and events  Can be implemented by a given class or structure  Define only the prototypes of the operations  No concrete implementation is provided  Can be used to define abstract data types  Can be inherited (extended) by other interfaces  Can not be instantiated 50
  • 51.
    Interfaces – Example 51 publicinterface IShape { void SetPosition(int x, int y); int CalculateSurface(); } public interface IMovable { void Move(int deltaX, int deltaY); } public interface IResizable { void Resize(int weight); void Resize(int weightX, int weightY); void ResizeByX(int weightX); void ResizeByY(int weightY); }
  • 52.
    Interfaces – Example(2) 52 public interface IPerson { DateTime DateOfBirth // Property DateOfBirth { get; set; } int Age // Property Age (read-only) { get; } void Print(); // Method for printing }
  • 53.
    Interface Implementation Classes andstructures can implement (support) one or several interfaces Implementer classes must implement all interface methods Or should be declared abstract 53 class Rectangle : IShape { public void SetPosition(int x, int y) { … } public int CalculateSurface() { … } }
  • 54.
    Interface Implementation (2) 54 classRectangle : IShape, IMovable { private int x, y, width, height; public void SetPosition(int x, int y) // IShape { this.x = x; this.y = y; } public int CalculateSurface() // IShape { return this.width * this.height; } public void Move(int deltaX, int deltaY) // IMovable { this.x += deltaX; this.y += deltaY; } }
  • 55.
  • 56.
    Abstract Classes • Abstractclasses 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 directly • Child classes should implement all abstract methods or be declared as abstract too 56
  • 57.
    Abstract Classes (2) •Abstract methods are empty methods without implementation  The implementation is intentionally left for the descendent classes • When a class contains at least one abstract method, it is called abstract class • Abstract classes model abstract concepts  E.g. person, object, item, movable object 57
  • 58.
    Abstract Class –Example 58 abstract class MovableShape : IShape, IMovable { private int x, y; public void Move(int deltaX, int deltaY) { this.x += deltaX; this.y += deltaY; } public void SetPosition(int x, int y) { this.x = x; this.y = y; } public abstract int CalculateSurface(); }
  • 59.
    Interfaces vs. AbstractClasses • C# interfaces are like abstract classes, but in contrast interfaces:  Can not contain methods with implementation  All interface methods are abstract  Members do not have scope modifiers  Their scope is assumed public  But this is not specified explicitly  Can not define fields, constants, inner types and constructors 59
  • 60.
    Abstract Classes –Example 60 public abstract class Animal : IComparable<Animal> { // Abstract methods public abstract string GetName(); public abstract int Speed { get; } // Non-abstract method public override string ToString() { return "I am " + this.GetName(); } // Interface method public int CompareTo(Animal other) { return this.Speed.CompareTo(other.Speed); } }
  • 61.
    Abstract Classes –Example (2) 61 public class Turtle : Animal { public override int Speed { get { return 1; } } public override string GetName() { return "turtle"; } } public class Cheetah : Animal { public override int Speed { get { return 100; } } public override string GetName() { return "cheetah"; } }
  • 62.
  • 63.
    Abstract Data Types •Abstract Data Types (ADT) are data types defined by a set of operations (interface) • Example: IList<T> in .NET Framework LinkedList<T> +Add(item : Object) +Remove(item : Object) +Clear() … «interface» IList<T> List<T> 63
  • 64.
    Inheritance Hierarchies • Usinginheritance 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 64
  • 65.
    UML Class Diagram– Example 65 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
  • 66.
  • 67.
    Encapsulation • Encapsulation hidesthe 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 67
  • 68.
    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; } 68
  • 69.
    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 69
  • 70.
    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 70
  • 71.
  • 72.
    Homework Problem 1. Schoolclasses 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 a name and unique class number. Classes have unique text identifier. Teachers have a name. Disciplines have a name, number of lectures and number of exercises. Both teachers and students are people. Students, classes, teachers and disciplines could have optional comments (free text block). Your task is to identify the classes (in terms of OOP) and their attributes and operations, encapsulate their fields and define the class hierarchy.
  • 73.
    Problem 2*. Studentsand workers Define abstract class Human with a first name and a last name. Define a new class Student which is derived from Humanand has a new field – grade. Define class Worker derived from Human with a new property WeekSalary and WorkHoursPerDay and a method MoneyPerHour() that returns money earned per hour by the worker. Define the proper constructors and properties for this hierarchy. Initialize a list of 10 students and sort them by grade in ascending order (use LINQ or OrderBy() extension method). Initialize a list of 10 workers and sort them by money per hour in descending order. Merge the lists and sort them by first name and last name.
  • 74.
    Problem 3. Animalhierarchy Create a hierarchy Dog, Frog, Cat, Kitten, Tomcat and define useful constructors and methods. Dogs, frogs and cats are Animals. All animals can produce sound (specified by the ISound interface). 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 produces a specific sound. Create arrays of different kinds of animals and calculate the average age of each kind of animal using a static method (you may use LINQ).
  • 75.
  • 76.
    Thank you Vladislav Hadzhiyski Email:Vladislav.Hadzhiyski@gmail.com

Editor's Notes

  • #6 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #7 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #8 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #16 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #17 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #18 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #19 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #21 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #22 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #23 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #24 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #25 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #27 26##
  • #31 30##
  • #32 31##
  • #67 66##
  • #72 71##