Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 68

OBJECT-ORIENTED

PROGRAMMING 2
Introduction to Object-Oriented
Programming
WHAT YOU WILL LEARN IN THIS
CHAPTER
What object-oriented programming is
How to use OOP techniques
How desktop applications rely on OOP
What Is an Object?
An object is a building block of an OOP application. This
building block encapsulates part of the application, which
can be a process, a chunk of data, or a more abstract
entity.
Objects in C# are created from types, The type of an
object is known by a special name in OOP, its class.
You can use class definitions to instantiate objects, which
means creating a real, named instance of a class
Example: Car, Rectangle, Box, Coffee
Object is an entity that has data (fields/attributes) and
behavior(function/method)
What Is a Class?
When you define
a class, you define
a blueprint for a
data type or
object
A class definition
starts with the
keyword class
followed by the
class name; and
the class body,
enclosed by a pair
of curly braces.
MEMBER DEFINITIONS
Defining Fields

Fields are defined using standard variable declaration format (with optional
initialization), along with the modifiers discussed previously:

class MyClass
{
public int MyInt;
}
Defining Properties

Properties are defined in a similar way to fields, but theres more to them. Properties,
as already discussed, are more involved than fields in that they can perform
additional processing before modifying state and, indeed, might not modify state
at all. They achieve this by possessing two function-like blocks: one for
getting the value of the property and one for setting the value of the property.
These blocks, also known as accessors, are defined using get and set keywords
respectively, and can be used to control the access level of the property.
public int MyIntProp
{
get
{
// Property get code.
}
set
{
// Property set code.
}
}
// Field used by property.
private int myInt;
// Property.
public int MyIntProp
{
get
{
return myInt;
}
set
{
// Property set code.
}
}
Member Functions and Encapsulation
Member variables are
attributes of an object and they
are kept private to implement
encapsulation. These variables
can only be accessed using the
public member functions.
A member function of a class
is a function that has its
definition or its prototype
within the class definition like
any other variable. It operates
on any object of the class of
which it is a member, and has
access to all the members of
a class for that object.
Access Modifiers for Class Definitions
MODIFIER DESCRIPTION
none or internal

Class is accessible only from within the current
project
public Class is accessible from anywhere
abstract or internal abstract
Class is accessible only from within the current
project, and cannot be instantiated, only derived
from
public abstract
Class is accessible from anywhere, and cannot be
instantiated, only derived from
sealed or internal sealed
Class is accessible only from within the current
project, and cannot be derived from, only
instantiated
public sealed
Class is accessible from anywhere, and cannot be
derived from, only instantiated
public abstract class MyClass
{
// Class members, may be abstract.
}
public sealed class MyClass
{
// Class members.
}
internal class MyBase
{
// Class members.
}
virtual The method can be overridden.
abstract The method must be overridden
in non-abstract derived classes (only permitted
in abstract classes).
override The method overrides a base
class method (it must be used if a method is
being overridden).
extern The method definition is found
elsewhere.
Constructors
A class constructor is
a special member
function of a class
that is executed
whenever we create
new objects of that
class.
A constructor will
have exact same
name as the class and
it does not have any
return type. Following
example explains the
concept of
constructor:

Destructors
A destructor is a special
member function of a
class that is executed
whenever an object of
its class goes out of
scope. A destructor will
have exact same name
as the class prefixed
with a tilde (~) and it
can neither return a
value nor can it take any
parameters.
Destructor can be very
useful for releasing
resources before
coming out of the
program like closing
files, releasing
memories etc.
Destructors cannot be
inherited or overloaded.

Static and Instance Class Members
As well as having members such as properties,
methods, and fields that are specific to object
instances, it is also possible to have static (also known
as shared)
Static members are shared between instances of a
class, so they can be thought of as global for objects
of a given class. Static properties and fields enable
you to access data that is independent of any object
instances, and static methods enable you to execute
commands related to the class type but not specific to
object instances. When using static members, in fact,
you dont even need to instantiate an object.
Inheritance
allows us to define a class in terms of another class,
which makes it easier to create and maintain an
application. This also provides an opportunity to reuse
the code functionality and fast implementation time.
In OOP terminology, the class being inherited from
(derived from) is the parent class (also known as the
base class)
Inheritance enables you to extend or create more
specific classes from a single, more generic base class.
Inheritance
The syntax used in C# for creating derived classes is as follows:
<acess-specifier> class <base_class>
{ ... }

class <derived_class> : <base_class>
{ ... }
Polymorphism
All objects instantiated from a derived class can
be treated as if they were instances of a parent
class.
often expressed as 'one interface, multiple
functions'.
Polymorphism can be static or dynamic. In static
polymorphism the response to a function is
determined at the compile time. In dynamic
polymorphism , it is decided at run-time.
Static Polymorphism
The mechanism of linking a function with an
object during compile time is called early
binding. It is also called static binding. C#
provides two techniques to implement static
polymorphism. These are:
Function overloading
Operator overloading

Function Overloading
You can have
multiple
definitions for
the same
function name in
the same scope.
The definition of
the function
must differ from
each other by the
types and/or the
number of
arguments in the
argument list.
Operator Overloading
You can redefine or
overload most of the
built-in operators
available in C#. Thus
a programmer can
use operators with
user-defined types as
well. Overloaded
operators are
functions with special
names the
keyword operator foll
owed by the symbol
for the operator
being defined
Dynamic Polymorphism
C# allows you to create abstract classes that are used to
provide partial class implementation of an interface.
Implementation is completed when a derived class
inherits from it. Abstract classes contain abstract
methods, which are implemented by the derived class.
The derived classes have more specialized functionality.
Please note the following rules about abstract classes:
You cannot create an instance of an abstract class
You cannot declare an abstract method outside an abstract
class
When a class is declared sealed, it cannot be inherited,
abstract classes cannot be declared sealed.

Dynamic Polymorphism
When you have a function
defined in a class that you
want to be implemented in an
inherited class(es), you
use virtual functions. The
virtual functions could be
implemented differently in
different inherited class and
the call to these functions will
be decided at runtime.
Dynamic polymorphism is
implemented by abstract
classes and virtual functions.

Interfaces
is a collection of public instance (that is, nonstatic)
methods and properties that are grouped together to
encapsulate specific functionality.
describes the behavior or capabilities of a C# class
without committing to a particular implementation of
that class.
define properties, methods and events, which are the
members of the interface. Interfaces contain only the
declaration of the members. It is the responsibility of
the deriving class to define the members. It often
helps in providing a standard structure that the
deriving classes would follow.
OOP TOOLS IN VISUAL STUDIO
The Class View Window
This window shows you the class hierarchy
of your application and enables you to see at a
glance the characteristics of
the classes you use.
OOP TOOLS IN VISUAL STUDIO
The Object Browser
The Object Browser is an expanded version of the Class View window,
enabling you to view other classes
available to your project, and even external classes.
OOP TOOLS IN VISUAL STUDIO
Adding Classes
OOP TOOLS IN VISUAL STUDIO
Class Diagrams
One powerful feature of VS that you havent looked at yet is the
capability to generate class diagrams from code and use them to
modify projects. The class diagram editor in VS enables you to
generate UML-like diagrams of your code with ease.

Features:

Classes are shown as blue boxes, including their name and type.
Interfaces are shown as green boxes, including their name and
type.
Inheritance is shown with arrows with white heads (and in some
cases, text inside class boxes).
Classes implementing interfaces have lollipops.
Abstract classes are shown with a dotted outline and italicized
name.
Sealed classes are shown with a thick black outline.
OOP TOOLS IN VISUAL STUDIO
CLASS LIBRARY PROJECTS
A project that contains nothing but classes (along with other relevant type definitions,
but no entry point) is called a class library.

Class library projects compile into .dll assemblies, and you can access their contents
by adding references to them from other projects
OBJECT-ORIENTED
PROGRAMMING 2
Basic Desktop Programming
Basic Desktop Programming
WHAT YOU WILL LEARN IN THIS CHAPTER
How to use the WPF designer
How to use controls for displaying information to the user, such as the
Label and TextBlock controls
How to use controls for triggering events, such as the Button control
How to use the controls that enable users of your application to enter text,
such as the TextBox control
How to use controls that enable you to inform users of the current state
of the application and allow the user to change that state, such as the
RadioButton and CheckButton controls
How to use controls that enable you to display lists of information, such as
the ListBox and ComboBox controls
How to use panels to lay out your user interfaces
Ways to create user interface in Visual Studio
Windows Forms
basic tool for creating applications that target classic
Windows
use
Windows Presentation Foundations (WPF)
provide a wider range of application types and attempts to
solve a number of problems with Windows Forms
is technically platform-independent, and some of its
flexibility can be seen in the fact that a subset of WPF
called Silverlight is used to create interactive web
applications
VS Tools in GUI Design
Window Designer
heart of the development of most graphical
Windows applications
In Windows Form, it is used to create a user
interface by dragging and dropping controls from
a Toolbox to your window, placing them where
you want them to appear when you run the
application
In WPF, the user interface can be done by
dragging and dropping controls with writing raw
XAML.
XAML
Extensible Application Markup Language (XAML, pronounced
zammel)
a language that uses XML syntax
(Extensible Markup Language (XML) is a technology for
storing data in a simple text format and use by .NET, from
describing the configuration of applications to
transporting information between web services)
and enables controls to be added to a user interface in a
declarative, hierarchical way
you can add controls in the form of XML elements, and
specify control properties with XML attributes.
a powerful way to declare user interfaces, it is not a
programming language
XAML
XAML is designed with todays powerful graphics cards in mind,
and as such it enables you to use all the advanced capabilities that
these graphics cards offer through DirectX. The following lists
some of these capabilities:
Floating-point coordinates and vector graphics to provide layout that
can be scaled, rotated, and otherwise transformed with no loss of
quality
2D and 3D capabilities for advanced rendering
Advanced font processing and rendering
Solid, gradient, and texture fills with optional transparency for UI
objects
Animation storyboarding that can be used in all manner of situations,
including user-triggered events such as mouse clicks on buttons
Reusable resources that you can use to dynamically style controls
XML Sample Code
<?xml version="1.0"?>
<books>
<book>
<title>Beginning Visual C# 2012</title>
<author>Karli Watson</author>
<code>7582</code>
</book>
<book>
<title>Professional C# 2012</title>
<author>Simon Robinson</author>
<code>7043</code>
</book>
</books>
XAML SAMPLE CODE
<Window x:Class="Ch15Ex01.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Hello World"
HorizontalAlignment="Left"
Margin="220,151,0,0"
VerticalAlignment="Top"
Width="75"/>
</Grid>
</Window
this example creates a window with a single button on it.
Both the window and the button display the text "Hello World"
XAML is a powerful way to declare user interfaces, it is not a programming language
<Window x:Class="Ch15Ex01.MainWindow"
Window element is the root element of the XAML file
http://schemas.microsoft.com/winfx/2006/xaml/presentation
Default namespace of WPF and declares a lot of controls that you are going
to use to create user interfaces.
http://schemas.microsoft.com/winfx/2006/xaml
namespace that declares the XAML language itself.
xmlns:sys="clr-namespace:System;assembly=mscorlib
namespace allows you to use the built-in types of the .NET Framework in
your XAML

WPF Controls
Controls combine prepackaged code and a
GUI that can be reused to create more
complex applications.
They can define how they draw themselves
by default and a set of standard behaviors.
Example: Label, Button, and TextBox controls
Adding Controls to a Window
Example
Add controls to the Design View by dragging
them from the Toolbox panel or by typing the
XAML manually.
Start by dragging a Button control from the Toolbox
onto the Design View. Notice how the text in the
XAML View is updated to reflect the change you
made.
Now drag another Button, but this time drop it in the
XAML View below the first Button, but above the
</Grid> tag.
Properties
all controls have a number of properties that are used
to manipulate the behavior of the control. Example;
height and width
Dependency Properties
property that is registered with the WPF property system
in such a way as to allow extended functionality. This
extended functionality includes, but is not limited to,
automatic property change notifications.
Attached Properties
is a property that is made available to each child object of
an instance of the class that defines the property.
Manipulating Properties
1. Start by selecting the second Button control in Design View;
this is the button that is currently filling the entire window.
2. You can change the name of the control in the Properties
panel at the very top. Change it to rotatedButton.
3. Under the Common node, change the Content to 2nd Button.
4. Under Layout, change width to 75 and height to 22.
5. Expand the Text node and change the text to bold by clicking
the B icon.
6. Select the first button and drag it to a position above the
second button. Visual Studio will assist with the positioning by
snapping the control.
7. Select the second button again, and hover the mouse pointer
over the top-left corner of it. The pointer changes to a quarter-
circle with arrows on both ends. Drag down until the button is
tilted down.

Manipulating Properties
The XAML code for the window should now look like this:
<Window x:Class="Ch15Ex01.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="222,125,0,0"
VerticalAlignment="Top" Width="75"/>
<Button x:Name="rotatedButton" Content="2nd Button" Width="75
Height="22"
FontWeight="Bold" RenderTransformOrigin="0.5,0.5" >
<Button.RenderTransform><TransformGroup><ScaleTransform/>
<SkewTransform/><RotateTransform Angle="-31.336"/><TranslateTransform/>
</TransformGroup></Button.RenderTransform>
</Button>
</Grid>
</Window>
9. Run the application by pressing F5. Try to resize the window. Notice that the second
button moves with the window, whereas the first button stays fixed.
Events
Handling Events
two basic ways to add a handler for an event.
use the Events list in the Properties window
type the name of the event directly in XAML and add the
name of the handler there.
Routed Events
WPF uses events that are called routed events. A
standard .NET event is handled by the code that has
explicitly subscribed to it and it is sent only to those
subscribers. Routed events are different in that they
can send the event to all controls in the hierarchy in
which the control participates
bobbling event - event travels up the control hierarchy
Ex. Button Grid Window
tunneling event - event travel in the other direction, that
is, from the root element to the control on which the
action was performed and by convention all events like
this are prefixed with the word Preview
Ex. PreviewMouseButtonDown event
Control Types
Two Types
Content controls,
a control that have Content property, such as the
Button control,
Items control,
a control that allows you to insert multiple controls as
content. Example: Grid control.
CONTROL LAYOUT
All content layout controls derive from the abstract Panel class. This class
simply defines a container that can contain a collection of objects that derive
from UIElement. All WPF controls derive from UIElement.
You cannot use the Panel class directly for control layout, but you can derive
from it if you want to.
Alternatively, you can use one of the following layout controls that derive
from Panel:
Canvas This control enables you to position child controls any way you see fit. It doesnt
place any restrictions on child control positioning, but nor does it provide any assistance in
positioning.
DockPanel This control enables you to dock child controls against one of its four edges.
The last child control fills the remaining space.
Grid This control enables flexible positioning of child controls. You can divide the layout of
this control into rows and columns, which enables you to align controls in a grid layout.
StackPanel This control positions its child controls in a sequential horizontal or vertical
layout.
WrapPanel This control positions its child controls in a sequential horizontal or vertical
layout as StackPanel, but rather than a single row or column of controls,
Stack Order
When a container control contains multiple child controls,
they are drawn in a specific stack order.
The first child in a container is placed on the lowest layer
in the stack, and the last child on the topmost layer.
Alignment, Margins, Padding, and Dimensions
Alignment determine how the control is aligned. Two
alignment properties, HorizontalAlignment (Left, Right,
Center, or Stretch)and VerticalAlignment (Top, Bottom,
Center, or Stretch),
Margin and Padding specify the space to leave blank
around the edges of controls and inside the edges of
controls, respectively.
Border
control is a very simple, and very useful, container
control. It holds a single child, not multiple children
Canvas
provides complete freedom over control positioning
and the HorizontalAligment and VerticalAlignment
properties used with a child element will have no
effect whatsoever over the positioning of those
elements.
Canvas
DockPanel
enables you to dock controls to one of its
edges.
DockPanel has a single attached property
that child controls can use to specify the edge
to which controls dock: DockPanel.Dock. You
can set this property to Left, Top, Right, or
Bottom.
StackPanel
slimmed down version of DockPanel, where
the edge to which child controls are docked is
fixed for those controls.

WrapPanel
essentially an extended version of
StackPanel; controls that dont fi t are
moved to additional rows (or columns).
Grid
Grid controls can have multiple rows and columns that you can use to lay out child controls.
You have used Grid controls several times already in this chapter, but in all cases you used a
Grid with a single row and a single column. To add more rows and columns, you must use
the RowDefinitions and ColumnDefinitions properties, which are collections of
RowDefinition ,respectively, and are specifi ed using property element syntax:
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>

</Grid>
The Image Control
Image is a very simple control that can be
used to great effect. It allows you to display a
single image and to resize this image as you
see fit. The control exposes two properties,
The Label Control
It displays simple text information to the user and in
some cases relays information about shortcut keys.
The control uses the Content property to display its
text. The Label control displays text on a single line.
If you prefix a letter with an underscore _ character,
the letter will become underlined and it will then be
possible to access the control directly by using the
prefixed letter and Alt.
For example, _Name assigns the shortcut Alt+N to any
control directly following the label.
The TextBlock Control
this control displays simple text without any
complicated formatting.
Unlike the Label, the TextBlock control is
capable of displaying multiple lines of text. It
is not possible to format individual parts of
the text.
The TextBlock displays the text even if it will
not fit in the space granted to the control.
The Button Control
This control is used everywhere and is easily
recognized on a user interface
The button does not contain any properties to
display images or text, but you can use the Content
property to display simple text or embed an Image
control in the content to display an image
<Button HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="10" >
<StackPanel Orientation="Horizontal">
<Image Source=".\Images\Delete_black_32x32.png" Stretch="UniformToFill
Width="16" Height="16" />
<TextBlock>Delete</TextBlock>
</StackPanel>
</Button>
The TextBox Control
These controls are designed exclusively for displaying text to the
user. The TextBox control allows the user to type text into the
application.
The CheckBox Control
CheckBoxes present the users with options
that they can select or clear. You should use a
CheckBox if you have want to present an
option to the users that can be turned on or
off, or want the users to answer yes or no to
a question.
The RadioButton Control
RadioButtons are used with other RadioButtons to
allow users to choose between multiple options
where only one can be selected at any time. You
should use RadioButtons when you want the users
to answer a question that has a very limited number
of possible values.
The ComboBox Control
ComboBoxes are commonly used to display
long lists of values and allow users to select
exactly one option in a drop-down list.
A ComboBox can be changed to display itself
with a TextBox at the top that allows the
users to type any values that they feel are
missing.
A ComboBox is an Items control, which
means that you can add multiple items to it.
ComboBox Properties
The TabControl
It is a layout control that is used to group
controls on pages that can be selected by
clicking on them.
Tab controls are used when you want to display
a lot of information in a single window but dont
want to clutter the view too much. In this case,
you should divide the information into groups of
related items and create a single page for each
group.
The ListBox Control
ListBoxes often allows the user to select
multiple items and display its content in a list
that is always expanded

You might also like