Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Object-Oriented Programming (OOP) is one of the most popular methodologies in software development. It offers a powerful model for creating computer programs. It speeds the program development process, improves maintenance, and enhances reusability of programs. This chapter introduces object-oriented methodology and discusses the concepts of objects, classes, messages, and methods. It provides an overview of the phases involved in object-oriented analysis and design. This chapter also explains how to define classes in C#.
Objectives
In this chapter, you will learn to: Explain features of the object-oriented methodology Describe the phases of the object-oriented methodology Define classes in C#
Chapter 1
Object-Oriented Methodology
Object-orientation is a software development methodology that is based on modeling a real-world system. An object is the core concept involved in object orientation. An object is the representation of a real-word entity or concept. For example, an employee, a window, a car, or a bird can be modeled as objects. You can think of an object-oriented model as a collection of objects and their inter-relationships.
Objects
An object literally means a material thing that is capable of being presented to the senses. For our purpose, an object is a tangible entity that may exhibit some well-defined behavior. For example, let us consider a tennis ball: A tennis ball is a tangible entity, with a visible boundary. A tennis ball has a specific defined purpose (such as bouncing). You can direct a specific action towards a tennis ball by hitting it with a racquet or by tossing it. But the definition of an object is not limited to merely something that can be seen, held, and touched, such as a tennis ball or a car. For the purpose of software development, the definition of an object needs refinement. For example, consider the Acme Nut and Bolt Company. An organization does not have a visible boundary, unlike a tennis ball. While it
NIIT
does not possess a physical boundary, it does have a conceptual boundary. Like all organizations, it has a specific defined purpose, and one can direct a specific action towards it. Thus, the Acme Nut and Bolt Company is an object. State, Behavior, and Identity of an Object According to Grady Booch, a renowned software architect, an object has the following characteristics: It has a state. It may display behavior. It has a unique identity. The state of an object is indicated by a set of attributes and their values. For example, a chemical can be characterized by its temperature, color, and density. The behavior of a chemical refers to the change of its attributes over a period of time. A chemical also has state, such as solid, liquid, or gas. The preceding paragraph explains the first two points of the definition of an object by Grady Booch An object has state, exhibits some well-defined behavior. Now, you will examine the next part of the definition - and has a unique identity. Each object has a unique identity, and the identity of an object distinguishes the object from all other objects. For example, you can take a car as an object. It can have states such as moving and stationary. It can accelerate, decelerate, turn right, or turn left, which is its behavior. The car also has an identity, such as a unique registration number. The following figure depicts the characteristics of a car.
State: Stationary
Behavior: Accelerate
Two objects may have the same behavior and state, but they will never have the same identity. The identity of an object does not change in its lifetime. For example, two tennis balls may have the same color, be made of the same material, have the same weight and the same circumference, and display the same behavior. However, they will have distinct
NIIT
identities (for example, one ball will have the factory seal number A189735 and the other S660794).
Just a minute:
Identify the possible states of the following objects: 1. 2. A cell phone A stereo
Answer:
1. 2. States of a cell phone: Off, Ring, Vibrate, and Call States of a stereo: Play, Pause, Rewind, and Forward
Classes
Look at the world around you. It is full of objects of various shapes, sizes, colors, and behavior. For example, the earth is inhabited by millions of animals. A zoologist cannot do any meaningful study of these objects without organizing this vast variety of animals found in the world in a logical manner. Thus, the zoologists have classified animals into kingdoms, genus, families, and species. All animals and birds, which are essentially objects, can be classified on the basis of their common attributes. For example, the peacock, the sparrow, and the kingfisher are all birds. All of them share characteristics that are common to the family of birds. All of them lay eggs, are covered with feathers, have hollow bone structures, and have the ability to fly. Therefore, they share structural and behavioral similarities and belong to the class called Birds.
NIIT
Peacock
Sparrow
The Class - Birds
Kingfisher
From the preceding example, you may define a class as a declaration, a template, or a blueprint that can be used to classify objects. Similarly, Book is a class and Gone with the Wind and Farewell to Arms are the objects of this class. Consider a video game that involves two players, Tom and Mark, who fight with each other. Tom chooses a shotgun and Mark chooses a pistol as their weapons in the game. If you need to create an object model for this game, you can identify a total of four objects. They are Tom, Mark, the shotgun, and the pistol. The object shotgun belongs to the class Firearms. It has certain attributes that are common with the pistol. However a shotgun is a unique object. Both the shotgun and the pistol are examples or instances of Firearms. Therefore, the shotgun and pistol are objects of the same class, as shown in the following figure.
Class: Firearms
Object: Pistol
Object: Shotgun
When Tom attacks Mark, Mark receives a message and reacts to that message. The reaction can be exhibiting a particular behavior such as running, hiding, dodging, or fighting back. For example, when Tom attacks, Mark receives a message Being Attacked. Mark responds to this message by hiding. In this situation, hiding is a behavior exhibited by Mark. Therefore, behavior (also called method in object-oriented methodology) is simply a set of actions taken by the receiving object in response to a message.
Just a minute:
Dr. James and Mr. Hyde went to the railway station to book tickets for 3rd December. At the railway station, they requested the clerk at the ticket counter to book two tickets for the Flying Express in the first class. Identify the following: 1. 2. The possible receiver of the message in this situation. The possible method that the receiver can use.
Answer:
1. 2. The receiver of the message in this case will be the clerk at the ticket counter. The clerk will check if two tickets are available on the requested train in the desired class and for the desired date. If the tickets are available, the clerk will enter the details (name, age, departure date, and seat), confirm the reservation, and collect the required fare.
NIIT
Realistic Modeling
Because you live in a world of objects, it logically follows that the object-oriented approach models the real world more accurately. The object-oriented approach allows you to identify entities as objects having attributes and behavior. Attributes and behavior typically depict how the object acts and reacts. For example, the car is an object belonging to the class Vehicle. The car has attributes such as speed, color, and power. It displays behavior such as being stationary, moving slowly, or accelerating.
Reusability
In the software industry, using existing classes or objects from other applications saves resources spent in recreating the classes from scratch. Consider the following analogy: Carcare is a leading car manufacturing company. Carcare manufactures two-seater cars that are very popular among the consumers aged between 20 and 24. The company has decided to enter the market of family segment market and has decided to manufacture a four-seater model. Carcare can either design a new car for the family segment or convert the two-seater model to a four-seater model. The cost involved in designing a new model is very high as compared to the cost involved in converting the two-seater model to a four-seater model.
NIIT
Therefore, the management and the design team may decide to convert the two-seater model into a family segment model, as shown in the following figure.
Two-seater Car
Attributes Behavior
Four-seater Car Two-seater Car: Attributes Two-seater Car: Behavior New Attributes New Behavior Example of Reusability
The preceding scenario depicts the concept of reusability that is supported by the object-oriented approach. The process of creating a new class by adding some features to an existing class is known as inheritance. The benefit of reusability translates to savings in time and effort, which in turn results in cost benefits.
Just a minute:
State whether the following situations demonstrate reusability: 1. 2. Recycling paper Pump reusability (same pump is used in a well and in a fuel station)
Answer:
1. IT does not represent reusability because the unusable paper is destroyed before paper is recycled for use. The unusable paper loses its identity and cannot be considered the same as recycled paper. It represents reusability because a pump can be used for suction of water as well as petrol. It is not necessary to use the same pump in both the cases. Two separate machines can be used because both belong to the Pump class.
2.
NIIT
Resilience to Change
The object-oriented approach allows systems to evolve. When a change is suggested, the old system need not be completely abandoned. Consider the example of JoyToys, Inc., is a company that manufactures toys for children in the age group of 1 to 12. Its car toys are popular with children because of their attractive colors, shape, and sound. For a couple of years, the company had no cause for complain about the design of the toy car. However, due to the advancement in technology and increasing competition, the designers now want to stop manufacturing the old car because the market requirements have changed. They want the company to manufacture a car that has flashing lights and is remotely controlled. In the object-oriented system, this requirement does not mean that the new car needs to be built from scratch. The new features can be easily incorporated in the old toy car without modifying the color, shape, and sound of the old toy car, as shown in the following figure.
Old Toy Car New Toy Car
Color
Shape
Sound
Color
Shape
Sound
Remote Control
Illustration of Resilience to Change
Flash Lights
Resilience to change also results in easier maintenance. This feature of object-oriented methodology is known as extensibility. The ability of a class to inherit features from another class also makes object-oriented programs more extensible. For the same reason, even during construction, parts of the system under development can be refined without any major changes to other parts.
NIIT
Note
Information is passed as parameters in a function. For a detailed study of functions and parameters, refer to the subsequent chapters.
If a car collides against an object, the behavior of the car after the collision will depend on the speed of the car and nature of the object that hit the car. For example, if the car collides with another car at high speed, both the cars will be smashed and the drivers might get injured. On the other hand, if a car collides with a street light at a slow speed, the impact would be less. This ability to react differently based on the information associated with the message is known as polymorphism.
NIIT
NIIT
the system. One of the end products of the analysis phase is the specification on how a system functions. In the analysis phase, the developer concentrates on obtaining as much information as a possible about the problem. The developer has to identify the critical requirements. Analysis, therefore, involves meeting and interviewing the concerned persons to understand systems that are currently in operation, and identifying all the causes of problems (if any) in the current system.
NIIT
Just a minute:
As a member of a team that is developing software for DialCom Telecommunications, Inc., you have been assigned the task of creating a software module that accepts and displays customer details such as name, age, and phone number. Identify the class that you will create and the methods of the class.
Answer:
As per the problem statement, the class required is: Customer The class should have the methods to: Accept customer details Display customer details
NIIT
Introducing C#
Computer languages have come a long way since the 1940s. Back then, scientists punched instructions into mammoth, room-sized computer systems. These instructions were long series of zeroes and ones. These machine language instructions are called the First Generation of computer languages. The 1950s saw the emergence of the Second Generation of computer languages assembly language - easier to write than machine language but still extremely complicated for a common man. However, the computer could still understand only machine language. Therefore, the Assembler software was developed to translate the code written in assembly language into machine language. In 1967, Martin Richard developed a language called BPCL for writing operating systems. An operating system is a set of programs that manages the resources of a computer and its interactions with users. The era of the Third Generation of computer languages had arrived. In 1970, Ken Thompson modified BPCL to create a new language called B. While working for Bell Laboratories, Thompson teamed up with Dennis Ritchie and wrote an early version of the Unix operating system for a DEC PDP-7 computer. Dennis Ritchie was working on a project to further develop the Unix operating system. He wanted a low-level language, like the assembly language, that could control hardware efficiently. At the same time, he wanted the language to provide the features of a high-level language, that is, it should be able to run on different types of hardware. B had performance drawbacks, so in 1972 he rewrote B and called it C. Therefore, C is categorized as both a Second and a Third Generation language. Thompson and Ritchie rewrote the Unix operating system in C. In the years that followed, C was widely accepted and used over different hardware platforms. This led to many variations of C. In 1989, the American National Standards Institute (ANSI), along with the International Standards Organization (ISO), approved a machine-independent and standard version of C. In the early 1980s, Bjarne Stroustrup of Bell Labs developed the C++ language. In his own words, "C++ was designed primarily so that my friends and I would not have to program in assembly, C, or various modern high-level languages. Its main purpose was to make writing good programs easier and more pleasant for the individual programmer." C++ was originally known as 'C with classes' because two languages contributed to its design: C, which provided low-level features, and Simula67, which provided the class concept. C++ is an object-oriented language. Other object-oriented languages are Java, Smalltalk, and C#. C#, also known as C-Sharp, is a programming language introduced by Microsoft. C# contains features similar to Java and C++. It is specially designed to work with Microsofts .NET platform.
NIIT
Note
The .NET platform is aimed at providing Internet users with Web-enabled interface for applications and computing devices such as mobile phones. It also provides developers the ability to create reusable modules, thereby increasing productivity.
Compilers
All languages have a vocabulary, which is a list of words that have a specific meaning in that language. Languages also have their own grammar rules, which state the rules for combining words to form sentences. This is what ensures that whatever is spoken in a particular language is interpreted similarly by all people who understand the language. Similarly, programming languages also have a vocabulary, which is referred to as the set of keywords of that language, and a grammar, which is referred to as the syntax. Does this mean that computers can directly interpret the instructions written in any programming language? No, they cannot. Then, how do you ensure that a computer executes the instructions from a program as intended? What would you do if you got hold of a recipe for a delicious dish written in a foreign language that you do not understand? You would get it translated to English or any other language you understand to be able to prepare the dish. Similarly, you need a translator to convert the instructions written in a programming language to machine language. A compiler is a special program that processes the statements written in a particular programming language and converts them into machine language. Like everything else in the computer, the compiler also follows the Input-Process-Output (I-P-O) cycle. It takes the programming language instructions as input. It processes these instructions to convert them to machine language. These instructions can then be executed by the computer. This process of conversion is called compilation. For each programming language, there is a different compiler available. For example, for compiling a program written in the C language, you require a C compiler. For a Java program, you require a Java compiler. For C# programs, you will use the csc compiler. You will now learn to create classes in the C# language.
NIIT
Classes in C#
Consider the following code example, which defines a class:
public class Hello { public static void Main(string[] args) { System.Console.WriteLine("Hello, World! \n"); } }
The preceding class declaration provides a method Main() that will display the message Hello, World! on your screen. The parts of the preceding code need to be examined.
NIIT
Class Naming Conventions in C# Class names should follow certain naming conventions or guidelines. A class name: Should be meaningful (strongly recommended). Should ideally be a noun. Can use either the Pascal case or Camel case. In Pascal case the first letter is capitalized and the rest of the letters are in lower case, such as Myclass. In Camel case the first letter is in lower case and the first letter of each subsequent word is capitalized, such as myClass. Rules for Naming Classes in C# Name of classes: Must begin with a letter. This letter may be followed by a sequence of letters, digits (0-9), or _. The first character in a class name cannot be a digit. Must not contain any embedded space or symbol like ? - + ! @ # % ^ & * ( ) [ ] { } . , ; : " ' / and \. However, an underscore (_) can be used wherever a space is required. Must not use a keyword for a class name. For example, you cannot declare a class called public.
System.Console.WriteLine()
Console is a class that belongs to the System namespace. A namespace is a collection of classes. The System namespace contains the method WriteLine(), which displays the enclosed text on the screen. The Console class has other methods, which are used for various input/output operations. The character (.) is used to access the function, WriteLine(), which is coded in the Console class of the System namespace. The preceding line can also be written as Console.WriteLine() if the statement using System is included as the first line of code. The following code is an example of Console.WriteLine():
Console.WriteLine("Hello World \n");
NIIT
The preceding code will display the following message on the screen:
Hello World
NIIT
Solution
The following code will create the Bike class with the required functions:
class Bike { void AcceptBikeDetails() { Console.WriteLine("Accepting Bike Details \n"); } void DisplayBikeDetails() { Console.WriteLine("Diplaying Bike Details \n"); } }
NIIT
Practice Questions
1. Which of the following is not a class? a. A Ford Ikon car with the registration number XXXX b. Fruit c. Mammal d. Fish Which method displays the message Hello People on the screen? a. Console.WriteLine("Hello People"); b. System.WriteLine("Hello People"); c. Console("Hello People") ; d. Console.writeline (Hello People) ; Console is a ________. a. Namespace b. Class c. Function d. Escape sequence character In a C# program, which is the first function to be executed? a. Main() b. main() c. Console.WriteLine() d. void Accept_bike_details() Which of the following is used to denote a newline character? a. \b b. \n c. \v d. /n
2.
3.
4.
5.
NIIT
Summary
In this chapter, you learned that: According to the object-oriented approach, systems consist of component objects that interact with each other. An object is an entity that may have a physical boundary. However, it should have the following characteristics: State Behavior Identity A class consists of a set of objects that share a common structure and behavior. If an object desires an action from another object, it sends a message to that object. The object that receives the message is called the receiver, and the set of actions taken by the receiver constitutes the method. The features of the object-oriented approach are: Realistic modeling Binding attributes and behavior together Reusability Resilience to change Existence as different forms A model of a system is built in the stages of analysis and design. The purpose of the model is to help developers understand the reality that they are trying to imitate. In C#, a class is created by using the keyword class. It is identified by a name called the class name. The Console.WriteLine() method is used to display text on the screen. Main() is the first function which is executed in a C# program. Escape characters are used to display special characters such as the newline character.
NIIT
Exercises
Exercise 1
Analyze the process of making a call by using a pay phone. Identify the objects involved and the behavior of these objects. Also, identify the messages passed between the objects for interacting with each other.
Exercise 2
As a member of a team that is developing an automated ranking system of players in video game parlors, you have been assigned the task of creating a module that accepts the details of the player after a game is over. Declare a class Player, which consists of three member functions: AcceptPlayerDetail(), ComparePlayerDetail(), and PrintPlayerRank(). Each of these functions should print the appropriate message on the screen.
NIIT
NIIT