More Related Content
Similar to Introduction to Object Oriented Concepts
Similar to Introduction to Object Oriented Concepts (20)
Introduction to Object Oriented Concepts
- 1. Slide 1
Introduction to
Object-Oriented Concepts
Module 1
In this module we will study the basics of OOP.
We will develop an understanding of classes, inheritance, & encapsulation.
We will look at attributes, properties, and methods.
We will discuss scope and access modifiers.
We will cover the concept of messages.
Module 1 1 Web OOC
©2006 SetFocus, LLC Version 1.0
- 2. Slide 2
Procedural vs OO Programming
Terminology:
Data Attributes
Behavior Procedures/Methods
Key Differences:
Procedural programming separates attributes from
behaviors that work with them.
Object-Oriented programming combines attributes
and behaviors into a single entity – an object.
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Module 1 2 Web OOC
©2006 SetFocus, LLC Version 1.0
- 3. Slide 3
Procedural Programming
Data is separate from behavior
Easy to modify data outside your scope
Global data
Little control over who accesses the data
Testing and debugging are more difficult
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Many programs have access to data and can modify it. No single set of
constraints.
A change to the data or the constraints imposed on the data may cause changes
in many programs. Each has to be re-tested.
Bad data allowed by one program may cause another to fail.
Module 1 3 Web OOC
©2006 SetFocus, LLC Version 1.0
- 4. Slide 4
Data Types
When we need to represent data in a program,
we pick a suitable variable type.
For numbers with integer values, we choose an
integer data type.
For numbers that represent currency, we might
choose a decimal data type.
For names and addresses, we would typically
choose a string data type.
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
We choose a data type based on it’s properties and available behaviors. Making
the correct choice results in adequate predictable behavior.
Module 1 4 Web OOC
©2006 SetFocus, LLC Version 1.0
- 5. Slide 5
User defined data types
In an object oriented environment we define
new data types as required
A class is a combination of the data elements
and behavior necessary to define a new data
type.
The source code defines a data type or class
An instance of the type is called an object
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Module 1 5 Web OOC
©2006 SetFocus, LLC Version 1.0
- 6. Slide 6
Abstraction
Selectively focusing on essential aspects
Reducing complex entity into only those
characteristics required to achieve a goal
A fundamental activity throughout the live of an
object oriented system is the identification and
refinement of the required abstractions
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Noun – representation of entity from problem domain.
Verb – process of reducing a concept to its essential elements.
Module 1 6 Web OOC
©2006 SetFocus, LLC Version 1.0
- 7. Slide 7
What is a Class?
Definition (code) of a new Data Type
Abstraction of a concept or entity
Blueprint for building an object
To instantiate (create) an object, you must have
a class that defines how the object should be
built
Think of a cookie-cutter for making cookies
Another viewpoint…
Class metadata
Object data
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Think of the Date class, the data required is the day, the month and the year.
Useful functionality for a good date class would incude:
Ability to subtract two dates
Ability to add (or subtract) x number of days, months, or years to a given date.
Ability to format a date into a string for printing in a variety of formats
Complete knowledge of calendar issues such as leap years and leap centuries.
The “Go To” place for storing and manipulating data that represents a day in
time.
With a good select selection of classes to choose from, engineering an
application becomes similar to engineering a car. The application is assembled
from an inventory of off the shelf parts. In an OO world, first we model the
elements in the problem domain as classes. These are typically “Entity” objects
such as customers, vendors, parts, invoices, orders, etc. Then we “wire” or
assemble an application by writing classes that perform the required business
processes we are automating, utilizing the entity objects we have already
modeled. An order entry system represents a business process utilizing entity
objects like customers, orders, vendors, and products.
Module 1 7 Web OOC
©2006 SetFocus, LLC Version 1.0
- 8. Module 1 8 Web OOC
©2006 SetFocus, LLC Version 1.0
- 9. Slide 8
What is an Object?
An instance of a Class
Fundamental building block to all object-oriented programs
Objects contain:
Data (Attributes)
Behavior (Methods)
State – current value of attributes – may impact behavior
Identity – Each instance is discrete regardless of state
Objects interact with by sending messages
Also known as performing a method call
Request for service from one object to another
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Just like I, j, and k might all be of type integer, e1, e2, and e3 might all be of type
Employee. The “Employee” class would be an abstraction of an employee and
would describe the data and behavior for an employee in the system. e1 might
be utilized to represent “John” and e2 might be used to represent “Alice”. e3
might exist but not yet be initialized to represent any specific Employee.
We create objects (allocate memory for them) also known as instantiation, with
the new keyword.
Employee e1 = new Employee(); // this line of code creates an object of type
Employee referred to by the variable e1. e1 is actually a reference ( an address,
a pointer) to an instance of type Employee somewhere in memory.
Module 1 9 Web OOC
©2006 SetFocus, LLC Version 1.0
- 10. Slide 9
Class Characteristics
Messages
Are the communication between objects
Classes are state-less, they don’t change
Is an abstract representation – captures
essential elements of some element from the
problem domain.
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Two key member types of a class are attributes and methods.
Module 1 10 Web OOC
©2006 SetFocus, LLC Version 1.0
- 11. Slide 10
Class Members
Attributes
Define what data is stored in an instance of an object
Ex. Person class defines name and address
Methods
Implements the required behavior for each object
More members on future slides
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Module 1 11 Web OOC
©2006 SetFocus, LLC Version 1.0
- 12. Slide 11
Attributes
Attributes are the data elements of an object
Each time you cerate a new object, memory is
allocated for each attribute
Attributes may be of any known data type.
Attributes remain in memory as long as the
containing object remains in memory.
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Attributes may be of any primitive type such as integers or floating point
numbers.
They may also be of any type (Class) in the provided libraries such as DateTime.
They may also be of any type (Class) that you create.
An objects attributes remain in memory from the time you create an object with
the new operator until the object is garbage collected. An object becomes
eligible for garbage collection when the program no longer has a reference to it.
Date d = new Date(); // create an instance of a date object.
d = null; // make the object eligible for garbage collection.
Module 1 12 Web OOC
©2006 SetFocus, LLC Version 1.0
- 13. Slide 12
Methods
Methods represent the procedures or functions
of an object
Methods have implicit access to all other
members of the class including attributes and
other methods
Variables declared within the method are local to
the method and cease to exist when the method
terminates
Arguments to methods are also local to the
method
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Methods are where the bulk of our code belongs.
When we declare a method, we must declare the return type, the method name,
and the names and types of any parameters. In addition the the required
elemens, there are some optional attributes we haven’t discussed yet.
Code Sample:
int AddTwo( int int1, int int2)
{
return int1 + int2;
}
In the above example AddTwo is the name of a method. It returns an int. It
takes two parameters of type int that will be referred to as int1 and int2.
Use the void keyword for the return type of a method that doesn’t return anything.
Unless your method is declared as returning void, you must have a return
statement and return something of the declared type.
Module 1 13 Web OOC
©2006 SetFocus, LLC Version 1.0
- 14. Any variables declared within a method are considered local variables. They
only live for the duration of the method and then can no longer be accessed. The
parameters to a method are also local variables.
Module 1 14 Web OOC
©2006 SetFocus, LLC Version 1.0
- 15. Slide 13
Accessing an Objects Members
Use the dot operator
From another object it would be ref.member
When a method gets called on an object, it gets
a reference to itself call this
To reference other members of the current
object, use the this reference
Using the this reference is usually optional
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Say we create a data object to represent John’s Birthday.
Code Sample:
DateTime BDay = new DateTime(); // create an instance of the DateTime
data type.
jBDay.day = 21; // set the day attribute to 21st
jBDay.month = 4 // set the month attribute to April
jBday.year = 1988; // set the year attribute to 1988
string sbday = jBDay.ToLongDateString(); // access a method to return
a formatted date.
Within the ToLongDateString() method you can use the this
reference to access the month attribute.
Code Sample:
String ToLongDateString()
{
. . .
string strMonth;
Module 1 15 Web OOC
©2006 SetFocus, LLC Version 1.0
- 16. switch ( this.month) // use of this. Is implied and therefore
optional here
{
case 1: strMonth = “January”; break;
case 2: strMonth = “February”; break;
. . .
}
Module 1 16 Web OOC
©2006 SetFocus, LLC Version 1.0
- 17. Slide 14
The Fraction Class Demo
Attributes - data
Methods – behavior
Instances
Messages
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Code Sample:
using System;
namespace Mod1Demo
{
class Fraction
{
// attributes
int numerator;
int denominator;
// methods
void Add( Fraction other )
{
this.numerator *= other.denominator;
this.numerator += this.denominator * other.numerator;
this.denominator *= other.denominator;
}
string AsString()
{
return this.numerator + "/" + this.denominator;
Module 1 17 Web OOC
©2006 SetFocus, LLC Version 1.0
- 18. }
static void Main(string[] args)
{
//int i = 5;
Fraction f1 = new Fraction();
f1.numerator = 3;
f1.denominator = 5;
Console.WriteLine( "f1 is " + f1.AsString() );
Fraction f2 = new Fraction();
f2.numerator = 1;
f2.denominator = 2;
Console.WriteLine( "f2 is " + f2.AsString() );
f1.Add( f2 );
Console.WriteLine( f1.AsString() );
}
}
}
Module 1 18 Web OOC
©2006 SetFocus, LLC Version 1.0
- 19. Slide 15
Encapsulation
Details not important to the use of the object
should be kept hidden
Classes have two main aspects:
Interfaces
Are made public to other objects
Implementations
Are made private to other objects
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Chapter 1, Encapsulation
Module 1 19 Web OOC
©2006 SetFocus, LLC Version 1.0
- 20. Slide 16
Object-Oriented Programming
Scope of data is kept to the object
Global data is rare, non-existant
Objects offer control over who accesses the data
Known as “data hiding” or “encapsulation”
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Module 1 20 Web OOC
©2006 SetFocus, LLC Version 1.0
- 21. Slide 17
More Encapsulation
Combine data and behavior necessary to fully
implement a concept or responsibility
Provide a “black box” implementation so user is
unaware of and not dependent on
implementation details.
Protect the data so that to an outside user, the
object is always in a stable allowed state.
When we refer to the state of an object, we are
talking about the value of its attributes.
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Encapsulation enables a user to focus on what an object does and not how it
does it.
Think about the Fraction class. Because division by zero is not defined, the
denominator of a fraction can not be zero. A good Fraction class would prevent
someone from setting its denominator to zero.
Module 1 21 Web OOC
©2006 SetFocus, LLC Version 1.0
- 22. Slide 18
Encapsulation Example
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
An electric socket is the encapsulation of home power. Do you know how the
power you use is generated? Is it generated with coal, nuclear, or natural gas?
When you plug in an appliance, do you really care? What it does is provide
electricity, how the power is generated and distributed is very complex but
plugging in an appliance and using the power is very easy.
Power users are not limited to plugging in toasters. Any appliance with the
proper cord can utilize the electric socket interface.
When we write OO code, we become more like engineers because we build re-
usable components.
Module 1 22 Web OOC
©2006 SetFocus, LLC Version 1.0
- 23. Slide 19
Access Modifiers
The public members of an object are exposed
and available for use by any code using the
object
The private members of an object can only be
accessed by other members of the defining class
There are other access modifiers besides public
and private that fall in between
Access Modifiers allow for data hiding which is
fundamental to encapsulation
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
For data hiding, make all attributes ( variables ) in your class private. Expose
those attributes that are part of the public interface via Properties or Methods.
Module 1 23 Web OOC
©2006 SetFocus, LLC Version 1.0
- 24. Slide 20
Properties
In addition to attributes and methods, a class
may define properties
Properties are usually associated with a
corresponding attribute
Properties allow users of an object to “get” and
“set” the value of an attribute indirectly. Code
in the set portion of a property my choose not to
change the associated attribute if the change
would validate constraints on the attribute.
Properties may also be “derived”.
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Properties enable us to indirectly expose the attributes of a class. With
properties we are able to enforce any constraints that may exist for an attribute.
Proper encapsulation implies that attributes be private and exposed via
properties with a more public access modifier.
A derived property is one without a corresponding attribute. You must calculate
the value. For instance, a person class may define attributes firstName and
lastName. The derived property LastFirst might return the last name
concatenated with a comma and the first name.
Module 1 24 Web OOC
©2006 SetFocus, LLC Version 1.0
- 25. Slide 21
The encapsulated Fraction
Add properties Numerator and Denominator
Add access modifiers
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Module 1 25 Web OOC
©2006 SetFocus, LLC Version 1.0
- 26. Slide 22
Using UML
Popular tool that assists
in designing classes
We’ll be using UML class
diagrams to illustrate how
classes are built
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
UML is maintained by OMG (http://www.uml.org/)
A UML diagram is to a programmer what a blueprint is to an engineer. It is a
symbolic picture of what we will be building. As in a complex building where one
blueprint does not attempt to describe everything, so it is with UML diagrams.
There a a variety of diagrams to aid in the design of an application.
Class diagrams help to understand the static nature of a class or associated
classes.
Package diagrams help understand the dependency between deployable
components.
Sequence diagrams help to understand the timing of messages between objects
Collaboration diagrams help to understand the relationships between objects.
State diagrams help to understand complicated state and state transition issues.
Activity diagrams help to understand process flow and responsibility
Use case Diagrams help to document and communicate the functionality of a
system.
Module 1 26 Web OOC
©2006 SetFocus, LLC Version 1.0
- 27. Module 1 27 Web OOC
©2006 SetFocus, LLC Version 1.0
- 28. Slide 23
UML for an Employee
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
This UML class diagram describes the attributes and methods of a simple
Employee Class.
The UML specification is intentionally flexible. In this diagram a class is
represented as a rectangle divided horizontally into multiple sections. This
diagram also defines the attributes, properties, and methods.
The top section with the name of the class is the only required section. A class
my define multiple types of members in addition to attributes and methods. A
class may also define events and inner classes. It is permissible to add a section
to describe any members of a class. It is also common to provide a section for
the responsibilities of a class.
In addition to the member names, you can specify data types, constraints, initial
values, and access modifiers.
Module 1 28 Web OOC
©2006 SetFocus, LLC Version 1.0
- 29. Slide 24
Practice 1.1
1. Characteristics of a Vehicle
2. Class Diagram
3. Encapsulation considerations
4. The Vehicle Class
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
PRACTICE 1.1
Object-Oriented Programming and Encapsulation
Objective
Learn to apply object-oriented practices to programming including the concept of encapsulation.
Exercise
In this exercise, we are going to model a vehicle using the object-oriented concepts discussed up
to this point.
Task 1
What are key characteristics of a vehicle?
Think of things that are common to all vehicles
What attributes should a vehicle have? What behaviors?
List the attributes and behaviors.
Task 2
Based on the results of the Task 1, model a vehicle in class diagram format using pencil and
paper. To reduce later coding effort, only pick about 4 or 5 attributes that you feel are the most
important.
Task 3
Should all the attributes and behaviors of the vehicle be part of the public interface?
If not, mark the appropriate members as either public or private.
Task 4
Module 1 29 Web OOC
©2006 SetFocus, LLC Version 1.0
- 30. Using the class diagram as a guide, create a C# class in Visual Studio that represents a vehicle.
Save the C# project and solution file. It will be used in the next practice. Make sure the
implementation is well encapsulated.
Module 1 30 Web OOC
©2006 SetFocus, LLC Version 1.0
- 31. Slide 25
Solution 1.1
You solution will not look like mine and that is
ok
Are your attributes private?
Do you have public properties exposing the
attributes?
Have you defined any methods to make
programming the application easier and more
consistent?
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Code Sample:
using System;
namespace M1_Practice1_1
{
public class Vehicle
{
private int speed;
private string direction;
private int passengers;
public int Speed
{
get { return speed; }
set { speed = value; }
}
public string Direction
{
get { return direction; }
set { direction = value; }
}
Module 1 31 Web OOC
©2006 SetFocus, LLC Version 1.0
- 32. public int Passengers
{
get { return passengers; }
set { passengers = value; }
}
public void Start()
{
Console.WriteLine( "Engine now started");
}
public string Turn( string direction )
{
Console.WriteLine( "Now turning " + direction );
Direction = direction;
return direction;
}
public void Accelerate( int additionalSpeed )
{
Speed += additionalSpeed;
Console.WriteLine("Now traveling at " + Speed);
}
public override string ToString()
{
return "Vehicle is traveling " + direction + " at " +
speed;
}
static void Main(string[] args)
{
Vehicle v1 = new Vehicle();
v1.Start();
v1.Accelerate( 30 );
v1.Accelerate( -20 );
Module 1 32 Web OOC
©2006 SetFocus, LLC Version 1.0
- 33. v1.Turn("Left");
v1.Turn("Strait");
v1.Accelerate( -10 );
Console.WriteLine( v1.ToString() );
}
}
}
Module 1 33 Web OOC
©2006 SetFocus, LLC Version 1.0
- 34. Slide 26
Inheritance
The definition for one class becomes the basis for defining a more
specialized version of the Class
Allows a class to inherit the members (attributes, properties, and
methods) of another class
Facilitates Code Reuse
Allows designs to factor out common functionality among classes
Ex. Mammal, Dog, Cat
Represent Is-A Relationships
Ex. Dog is a Mammal
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
In C#, use a colon to indicate inheritance.
Code Sample:
class Shape
{
int x;
int y;
}
class Triangle: Shape { } // Triangle inherits from Shape
class Circle: Shape{} // Circle inherits from Shape
Module 1 34 Web OOC
©2006 SetFocus, LLC Version 1.0
- 35. Slide 27
Inheritance Terminology
Superclass Parent/base/super class
Contains all the attributes/methods that child classes
will inherit
Subclass
Child/derived/sub class
Inherits attributes/methods from the parent class
Can define new attributes/methods specific to the
child class
Can override or modify inherited methods
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
C# and .NET terminology often uses Base/Derived
Module 1 35 Web OOC
©2006 SetFocus, LLC Version 1.0
- 36. Slide 28
Inheritance in C#
All classes implicitly inherit from the class System.Object
(object) if you don’t specify a parent
Classes inherit several methods from object including
Equals, GetHashCode, and ToString
Within a child class, we can override ( replace ) the
implementation of inherited methods so that they
perform in a way more characteristic of the child.
C# supports single inheritance (only one base class)
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Code Sample:
class Fraction: object // compiler assume object if you don’t specify
a parent
{
. . .
}
Module 1 36 Web OOC
©2006 SetFocus, LLC Version 1.0
- 37. Slide 29
Polymorphism
Literally means “many forms”
Closely related to inheritance
Subclasses can respond differently to messages
Child class overrides implementation of method
inherited from parent
Subclass can be substituted for a parent
Ex. Shape s = new Circle();
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Chapter 1, Polymorphism
C# requires use of the virtual/override keywords to implement polymorphism. By
default, not all methods in C# can be polymorphic.
Code Sample:
public abstract class Shape
{
public virtual double GetArea()
{
return 0.0; //Don’t know how to calculate the area of a
Shape
}
}
class Circle : Shape {
public override double GetArea()
{
return 3.14159 * radius * radius; // formula for the area
of a circle is PI * r squared.
Module 1 37 Web OOC
©2006 SetFocus, LLC Version 1.0
- 39. Slide 30
Benefits of Polymorphism
Allows developer to think and work at a higher
level of abstraction.
Helps eliminate code constructs like switch/case
where the purpose of the code is to determine
what code is to be executed and allows
developer to spend a larger percentage of time
writing code that advances the solution.
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Module 1 39 Web OOC
©2006 SetFocus, LLC Version 1.0
- 40. Slide 31
Associations
Relationship between objects
May be uni-directional or by-directional
Defines a Has-A relationship
Have multiplicity constraints defining the allowed
count of objects at either end of the association
May define the roll an associated object plays
Typically a pier to pier relationship but a
Composition defines a hierarchical relationship
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
When modeling a Person, we may add an attribute representing the collection of
cars owned by the Person. If the cars do not have an attribute indicating who
there owner is, we have a uni-directional association. Multiplicity would indicate
that a person could own from zero to an unspecified number of cars (0-*). If
there were a relationship defined between a person and his parents, multiplicity
on the parent end would be 2. All persons have a biological mother and father.
If the car class also had an attribute indicating who the owner was, it would be a
bi-directional association.
It is also common to label the associations between two objects with their roles.
A Person may play the role of “owner” as far as the car is concerned.
A Person may have a relationship with another Person playing the role of mother.
Module 1 40 Web OOC
©2006 SetFocus, LLC Version 1.0
- 41. Slide 32
Composition
Objects often contain other objects
Ex. Television contains tuner and video display
Objects built (composed) of other objects is
known as composition
Defines Whole-Pare relationship where part is
fully encapsulated by the whole
Lifetime of the parts coincides with the live of
the whole
Most common mechanism for reuse of code
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Code Sample:
class shape
{
int x;
int y;
// use an instance of the string class to hold the id
string id; // string is an alias for the class System.String
}
Module 1 41 Web OOC
©2006 SetFocus, LLC Version 1.0
- 42. Slide 33
UML With inheritance
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Employee inherits from Person
The Person class is composed of a ContactInfo object and an Address object
The Employee is composed of zero or more TaxInfo objects
The Employee is aware of the department he is in and can send messges to his
department object.
Department objects are aware of the Employees in the Department and can send
messages to the Employees.
Module 1 42 Web OOC
©2006 SetFocus, LLC Version 1.0
- 43. Slide 34
Inheritance/Polymorphism
Demo
The Shape class
ToString method
GetArea method
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Code Sample:
using System;
namespace InheritanceDemo
{
public class Shape // : object is implied
{
public int x, y;
public string id;
public override string ToString()
{
return "ID:" + id + " at " + x + " : " + y;
}
public virtual double GetArea()
{
return 0.0;
}
}
public class Circle : Shape
Module 1 43 Web OOC
©2006 SetFocus, LLC Version 1.0
- 44. {
public double radius;
public override double GetArea()
{
return 3.14 * this.radius * this.radius;
}
public override string ToString()
{
return "Circle -- " + base.ToString () +
" With Radius " + radius;
}
}
public class Rectangle : Shape
{
public int length, width;
public override double GetArea()
{
return this.length * this.width;
}
}
class Class1
{
static void Main(string[] args)
{
Console.WriteLine("Inheritance Demo");
Shape s1 = new Shape();
s1.x = 3;
s1.y = 5;
s1.id = "Shape 1";
Circle c1 = new Circle();
c1.x = 8;
c1.y = 10;
c1.id = "Circle 1";
c1.radius = 4.7;
Module 1 44 Web OOC
©2006 SetFocus, LLC Version 1.0
- 45. Rectangle r1 = new Rectangle();
r1.x = 32;
r1.y = 15;
r1.id = "Rect1";
r1.length = 5;
r1.width = 7;
Shape[] shapes = { s1, c1, r1 };
foreach( Shape s in shapes )
{
Console.WriteLine( s.ToString() );
Console.WriteLine( "Area is " + s.GetArea() );
}
}
}
}
Module 1 45 Web OOC
©2006 SetFocus, LLC Version 1.0
- 46. Slide 35
Practice 1.2
Inheritance and Polymorphism
The Airplane class analysis
Corrections to the Vehicle class
UML class diagram
Design for Encapsulation
Create the Airplane class
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
PRACTICE 1.2
Inheritance and Polymorphism
Objective
Learn to apply inheritance to existing class.
Exercise
Using the Vehicle class defined in the last practice, we will create a new class that will inherit the
characteristics of a vehicle and extend it with new characteristics.
There are many different types of vehicles. One common vehicle type is an airplane ( or a boat or
car). In this exercise, we will define a new sub-class class using the Vehicle class providing
common functionality for vehicles and planes.
Task 1
What characteristics do airplanes have that differentiate them from the vehicle type we defined in
Practice 1.1?
List the new attributes and behaviors.
Task 2
Now that you are designing specific specializations of the Vehicle class you may have discovered
that you did not think generally enough when doing lab 1.1. This is common but must be
corrected now. If necessary, update your Vehicle UML diagram and corresponding class.
Task 3
Based on the results of Task 1, create a class diagram for the Airplane ( or boat or car) class. Be
sure to include the Vehicle class in the diagram. Note: Use an arrow to denote inheritance.
Task 4
Module 1 46 Web OOC
©2006 SetFocus, LLC Version 1.0
- 47. Consider access modifiers and properties necessary for proper encapsulation of the new
members in the Airplane class.
Should any of the members defined in Vehicle be overridden in the Airplane class?
Task 5
Add an Airplane class to the solution created in Practice 1.1. Use the class diagram as a guide.
Module 1 47 Web OOC
©2006 SetFocus, LLC Version 1.0
- 48. Slide 36
Practice 1.2 Solution
You solution will not look like mine and that is
ok
Are your attributes private?
Do you have public properties exposing the
attributes?
Have you defined any methods to make
programming the application easier and more
consistent?
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Code Sample:
public class Airplane : Vehicle
{
private int altitude;
public int Altitude
{
get { return altitude; }
set { altitude = value; }
}
private void PrepareToLand()
{
while (Speed > 120 || altitude > 5000)
{
if ( altitude > 5000) altitude -= 500;
if ( Speed > 120 ) Speed -= 50;
Console.WriteLine("Preparing to land " +
ToString() );
}
Speed = 120;
Altitude = 5000;
}
Module 1 48 Web OOC
©2006 SetFocus, LLC Version 1.0
- 49. public void Land()
{
PrepareToLand();
while ( altitude > 0)
{
Console.WriteLine("Decending - " +
ToString());
altitude -= 500;
}
while (Speed > 0)
{
Console.WriteLine("Stopping -" + ToString() );
Speed -= 40;
}
Speed = 0;
altitude = 0;
Console.WriteLine("The plane has landed." +
ToString());
}
public override string ToString()
{
return "The airplane is" + base.ToString() + " at
altitude " + altitude;
}
public void Takeoff()
{
while (Speed < 120 )
{
Console.WriteLine( "Taking off " + ToString()
);
Speed += 40;
}
while (altitude < 5000)
Module 1 49 Web OOC
©2006 SetFocus, LLC Version 1.0
- 50. {
Console.WriteLine( "Taking off " + ToString()
);
altitude += 500;
Speed += 25;
}
Console.WriteLine("The plane is flying");
}
static void Main(string[] args)
{
Airplane a1 = new Airplane();
a1.Start();
a1.Direction = "Straight";
a1.Takeoff();
a1.Speed +=100;
a1.Altitude +=2000;
Console.WriteLine( a1.ToString() );
a1.Land();
}
}
Module 1 50 Web OOC
©2006 SetFocus, LLC Version 1.0
- 51. Slide 37
Lab 1 – SongPlayer Lab
Create a new project
Define the Song class
The KaraokeSong sub-class
A Main method for testing
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
LAB 1
Introduction to Object-Oriented Concepts
Objective
Apply the object-oriented concepts of encapsulation, inheritance, and polymorphism.
Exercise 1
Build classes that will serve as a component to a music playback system.
The first class we need is a class to represent songs in the system.
Task 1
Create a new C# console project called SongPlayerLab.
Task 2
Add a new class to the project. Name the class Song. This will represent songs in our system.
Task 3
There are three main attributes that our Song class requires to represent a song. The attributes are:
title : string
artist : string
duration : int
Add each attribute to the Song class.
Task 4
To simplify displaying a Song to the console, we can create a method in the song class that will return the following
information about a song.
<Title> : <Artist> : <Duration> seconds
Ex.
All You Need Is Love : Beatles : 241 seconds
Call the method GetSongDetails. This method should return a string and take no arguments.
Exercise 2
Module 1 51 Web OOC
©2006 SetFocus, LLC Version 1.0
- 52. Our music playback system may support other capabilities. An ever popular past time is karaoke. To represent this extra
functionality, we can add another class to the system called KaraokeSong. However, we do not want to duplicate the
functionality of our existing Song class. Inheritance will play a role.
Task 1
Add a new class to the project. Name the class KaraokeSong. The class should inherit from Song.
Task 2
Participants in karaoke need to be able to see the lyrics of the song. To provide this functionality, another attribute is
required.
Add the following attribute to the KaraokeSong class:
lyrics : string
Task 5
As in the previous exercise, we would like to make it easy to display a karaoke song to the console. Because the Song
class provides this functionality, we do not need to do anything further.
You may ask, “What about the lyrics?” If required by the application, lyrics can be displayed by accessing the proper
accessor. In the common case for display a karaoke song such as in a track listing, the lyrics are not required. We’ve
made the design decision not to include them.
Exercise 3
We need some basic code to test out the classes.
Task 1
Inside the Main method, add code that creates an instance of each Song and KaraokeSong. Initialize all the attributes of
each object.
Task 2
Display to the console the Song and KaraokeSong objects by sending a message to their GetSongDetails() method.
Task 3
Make sure you save a copy of this project. You will be returning to it in future labs.
Module 1 52 Web OOC
©2006 SetFocus, LLC Version 1.0
- 53. Slide 38
Lab 1 Solution
Song Class
KaraokeSong Class
Testing from Main
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Code Sample:
using System;
namespace SongPlayerLab
{
public class Song
{
private string artist;
private string title;
private int duration;
public string Artist
{
get { return artist; }
set { artist = value; }
}
public string Title
{
get { return title; }
set { title = value; }
}
Module 1 53 Web OOC
©2006 SetFocus, LLC Version 1.0
- 54. public int Duration
{
get { return duration; }
set { duration = value; }
}
public string GetSongDetails()
{
return title + " : " + artist + " : " + duration;
}
}
public class KaraokeSong : Song
{
private string lyrics;
public string Lyrics
{
get { return lyrics; }
set { lyrics = value; }
}
}
class Class1
{
static void Main(string[] args)
{
Song s1 = new Song();
s1.Artist = "Beatles";
s1.Title = "All you need is Love";
s1.Duration= 185;
Console.WriteLine( s1.GetSongDetails() );
Song s2 = new KaraokeSong();
s2.Title= "Puff the Magic Dragon";
s2.Artist = "Peter, Paul and Mary";
s2.Duration= 180;
Module 1 54 Web OOC
©2006 SetFocus, LLC Version 1.0
- 56. Slide 39
Review
Data Types/Classes/objects
Attributes/properties/methods
Encapsulation/Inheritance/Polymorphism/Abstraction
Scope/Access Modifiers
Public/private
Associations/Composition
Methods of Object
ToString/Equals/GetHashCode
INTRODUCTION TO OBJECT-ORIENTED CONCEPTS SETFOCUS, LLC
Module 1 56 Web OOC
©2006 SetFocus, LLC Version 1.0