24
Lecture 5 What is object-oriented programming OOP techniques How Windows Forms applications rely on OOP

What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Lecture 5

What is object-oriented programming

OOP techniques

How Windows Forms applications rely on OOP

Page 2: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

OOP programming often simplifies things by providing an agreement about the approach to

data representation as well as about the structure and usage of more abstract entities. For

example, an agreement can be made not just on the format of data that should be used to

send output to a device such as a printer, but also on the methods of data exchange with

that device, including what instructions it understands, and so on.

WHAT IS OBJECT-ORIENTED PROGRAMMING?

Page 3: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

An object is a building block of an OOP application. This building block encapsulates part of

the application, which may be a process, a chunk of data, or a more abstract entity. In the

simplest sense, an object may be very similar to a struct type, containing members of

variable and function types. The variables contained make up the data stored in the object,

and the functions contained allow access to the object’s functionality. Slightly more

complex objects might not maintain any data; instead, they can represent a process by

containing only functions.

Objects in C# are created from types, just like the variables you’ve seen already. 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. The phrases

instance of a class and object mean the same thing here; but class and object mean

fundamentally different things.

What Is an Object?

Page 4: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Properties and Fields

Properties and fields provide access to the data contained in an object. This object data

is what differentiates separate objects because it is possible for different objects of the

same class to have different values stored in properties and fields.

Both fields and properties are typed, so you can store information in them as string

values, as int values, and so on. The range of valid values can be limited for a property,

but a field can take any value of its respective data type.

Page 5: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Methods

Method is the term used to refer to functions exposed by objects. These may be

called in the same way as any other function and may use return values and

parameters in the same way.

Methods are used to provide access to the object’s functionality. Like fields and

properties, they can be public or private, restricting access to external code as

necessary. They often make use of an object’s state to affect their operations, and

have access to private members, such as private fields, if required.

Page 6: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Everything’s an Object

At this point, it’s time to come clean: You have been using objects, properties, and

methods throughout this course. In fact, everything in C# and the .NET

Framework is an object! The Main() function in a console application is a method

of a class.

Every variable type you’ve looked at is a class. Every command you have used

has been a property or a method, such as <String>.Length, <String>.ToUpper(),

and so on. (The period character here separates the object instance’s name from

the property or method name, and methods are shown with () at the end to

differentiate them from properties.)

Objects really are everywhere, and the syntax to use them is often very simple. It

has certainly been simple enough for you to concentrate on some of the more

fundamental aspects of C# up until now. From this point on, you’ll begin to look at

objects in detail.

Page 7: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

The Life Cycle of an Object

Every object has a clearly defined life cycle. Apart from the normal state of ‘‘being

in use,’’ this life cycle includes two important stages:

Construction: When an object is first instantiated it needs to be initialized. This

initialization is known as construction and is carried out by a constructor function,

often referred to simply as a constructor for convenience.

Destruction: When an object is destroyed, there are often some clean-up tasks to

perform, such as freeing memory. This is the job of a destructor function, also

known as a destructor.

Page 8: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

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)

members, which may be methods, properties, or fields. 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 don’t even need to instantiate an object.

For example, the Console.WriteLine() and Convert.ToString()methods

you have been using are static. At no point do you need to instantiate the Console

or Convert classes (indeed, if you try, you’ll find that you can’t, as the constructors of

these classes aren’t publicly accessible).

Page 9: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Life Cycle of an Object

Every object has a clearly defined life cycle. Apart from the normal state of ‘‘being in use,’’

this life cycle includes two important stages:

Construction: When an object is first instantiated it needs to be initialized. This

initialization is known as construction and is carried out by a constructor function, often

referred to simply as a constructor for convenience. All class definitions contain at least

one constructor. These constructors may include a default constructor, which is a

parameterless method with the same name as the class itself. A class definition might

also include several constructor methods with parameters, known as nondefault

constructors. These enable code that instantiates an object to do so in many ways,

perhaps providing initial values for data stored in the object.

Destruction: When an object is destroyed, there are often some clean-up tasks to

perform, such as freeing memory. This is the job of a destructor function, also known

as a destructor. Destructors are used by the .NET Framework to clean up after objects.

In general, you don’t have to provide code for a destructor method; instead, the

default operation does the work for you. However, you can provide specific instructions

if anything important needs to be done before the object instance is deleted.

Page 10: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Static Class and Instance of a Class

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) members, which

may be methods, properties, or fields. Static members are shared between instances of a

class, so they can be thought of as global for objects of a given class.

Non-static members (instances) of a class are created separately. You can have many

instances of the same class. Since the properties and fields of an instance of a class are

not shared they can differ from one instance to the next.

Page 11: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Interfaces

An interface is a collection of public instance (that is, nonstatic) methods and properties that aregrouped together to encapsulate specific functionality. After an interface has been defined, you canimplement it in a class. This means that the class will then support all of the properties andmembers specified by the interface.

Interfaces cannot exist on their own. You can’t ‘‘instantiate an interface’’ as you can a class. Inaddition, interfaces cannot contain any code that implements its members; it just defines themembers themselves. The implementation must come from classes that implement the interface.

Page 12: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Disposable Objects

One interface of particular interest is IDisposable. An object that supports the

IDisposable interface must implement the Dispose() method — that is, it must provide

code for this method. This method can be called when an object is no longer needed

(just before it goes out of scope, for example) and should be used to free up any

critical resources that might otherwise linger until the destructor method is called on

garbage collection. This gives you more control over the resources used by your

objects.

Page 13: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Inheritance

Inheritance is one of the most important features of OOP. Any class may inherit

from another, which means that it will have all the members of the class from

which it inherits. In OOP terminology, the class being inherited from (derived from)

is the parent class (also known as the base class). Classes in C# may derive only

from a single base class directly, although of course that base class may have a

base class of its own, and so on.

Page 14: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Polymorphism

Polymorphism is an extremely useful technique for performing tasks with a

minimum of code on different objects descending from a single class. It isn’t just

classes sharing the same parent class that can make use of polymorphism. It is

also possible to treat, say, a child and a grandchild class in the same way, as long

as there is a common class in their inheritance hierarchy.

As a further note here, remember that in C# all classes derive from the base class

object at the root of their inheritance hierarchies. It is therefore possible to treat all

objects as instances of the class object.

Although you can’t instantiate interfaces in the same way as objects, you can have a

variable of an interface type. You can then use the variable to access methods and

properties exposed by this interface on objects that support it.

Page 15: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Collections

Collections are implemented as classes in much the same way as other objects.

They are often named in the plural form of the objects they store — for example, a

class called emps might contain a collection of emp objects. The main difference

from arrays is that collections usually implement additional functionality, such as

Add() and Remove() methods to add and remove items to and from the collection.

There is also usually an Item property that returns an object based on its index.

Page 16: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Events

Objects may raise (and consume) events as part of their processing. Events are important

occurrences that you can act on in other parts of code, similar to (but more powerful than)

exceptions. You can create event-driven applications, which are far more prolific than you

might think. For example, bear in mind thatWindows-based applications are entirely

dependent on events. Every button click or scroll bar drag you perform is achieved through

event handling, as the events are triggered by the mouse or keyboard.

Page 17: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Defining Classes

class MyClass

{

// Class members.

}

internal class MyClass

{

// Class members.

}

public class MyClass : MyBase

{

// Class members.

}

public abstract class MyClass

{

// Class members.

}

public sealed class MyClass

{

// Class members.

}

defines a class called MyClass

By default classes are internal which means

that only code in the current project will

have access to the members of the class

We can specify a class a public to make it

accessible from other projects

Abstract classes cannot be instantiated,

only inherited.

While sealed classes can be instantiated but

not inherited.

When a class inherits from another class the

base class name is included in the class

declaration

Page 18: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Multiple Inheritance

Although C# does not support multiple inheritance (i.e. deriving from more than one class) a

class can make use of multiple interfaces.

The correct way to specify a base class and an interface is as follows:

public class MyClass : MyBase, IMyInterface

{

// Class members.

}

Remember that multiple interfaces are possible, so the following is also valid:

public class MyClass : MyBase, IMyInterface, IMy2ndInterface

{

// Class members.

}

Page 19: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP
Page 20: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace complexClassDemo

{

public abstract class MyBase

{ }

internal class MyClass : MyBase

{ }

public interface IMyBaseInterface

{ }

internal interface IMyBaseInterface2

{ }

internal interface IMyInterface : IMyBaseInterface, IMyBaseInterface2

{ }

internal sealed class MyComplexClass : MyClass, IMyInterface

{ }

class Program

{

static void Main(string[] args)

{

MyComplexClass myObj = new MyComplexClass();

Console.WriteLine(myObj.ToString());

Console.ReadKey();

}

}

}

Complex Class Demo

Page 21: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

Auto-Generated Class Diagram

Page 22: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

SYSTEM.OBJECT

Because all classes inherit from System.Object, all classes have access to the

protected and public members of this class. Therefore, it is worthwhile to take a look at

what is available there. System.Object contains the methods described in the table in

Chapter 9 (pg. 215) of the textbook.

Object()

~Object()

Equals(object)

Equals(object,object)

ReferenceEquals(object,object)

ToString()

MemberwiseClose()

GetType()

GetHashCode()

Page 23: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

CLASS LIBRARY PROJECTS

As well as placing classes in separate files within your project, you can also place them in

completely separate 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 (which might be part of the same solution, but don’t

have to be). This extends the encapsulation that objects provide because class libraries may be

revised and updated without touching the projects that use them.

Page 24: What is object-oriented programming OOP techniques How ...csclab.murraystate.edu/~bob.pilgrim/325/lectures/lecture_05.pdf · Inheritance is one of the most important features of OOP

INTERFACES VERSUS ABSTRACT CLASSES

Interfaces and Abstract Classes are similar in a number of ways. Both abstract classes and

interfaces may contain members that can be inherited by a derived class. Neither interfaces nor

abstract classes may be directly instantiated, but you can declare variables of these types.

Now the differences: derived classes may only inherit from a single base class, which means that

only a single abstract class can be inherited directly. Conversely, classes can use as many

interfaces as they want.

Abstract classes may possess both abstract members and non-abstract members.

Interface members, conversely, must be implemented on the class that uses the interface — they

do not possess code bodies. Moreover, interface members are by definition public (because they

are intended for external use), but members of abstract classes may also be private (as long as

they aren’t abstract), protected, internal, or protected internal. In addition, interfaces can’t

contain fields, constructors, destructors, static members, or constants.

THAT'S ENOUGH OF THAT!