Tải bản đầy đủ (.pdf) (18 trang)

Creating Objects pot

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (637.52 KB, 18 trang )

Creating Objects
Chapter 2
An object is an instance of a class. You create
objects to access member variables and member
functions of a class.
The chapter discusses how to declare variables. It
also discusses how to write and execute C# program.
In this chapter, you will learn to:
 Declare variables
 Write and execute C# programs
Objectives

¤NIIT Creating Objects 2.3
N
ote
A variable is a location in the memory that has a name and contains a value. The value
could be an integer, such as 27, a decimal, such as 9.85, or a character, such as 'L'. A
variable is associated with a data type that defines the type of data, which can be stored in
a variable. For example, a variable called TennisPlayerName will ideally store characters,
whereas a variable called High_Score will store numbers. A program refers to a variable
by its name.
The following rules are used for naming variables in C#:
 Must begin with a letter or an underscore (‘_’), which may be followed by a
sequence of letters, digits (0-9), or underscores. The first character in a variable name
cannot be a digit.
 Should not contain any embedded spaces or symbols such as ? ! @ # + - % ^ & * ( ) [
] { } . , ; : " ' / and \. However, an underscore can be used wherever a space is
required, like high_score.
 Must be unique. For example, to store four different numbers, four unique variable
names need to be used. Uppercase letters are considered distinct from lowercase
letters.


 Can have any number of characters.
 Keywords cannot be used as variable names. For example, you cannot declare a
variable named
class because it is a keyword in C#.
The following are examples of valid variable names:
Game_level
High_score
This_variable_name_is_very_long
The following are examples of invalid variable names:
#score
2strank
C# is a case-sensitive language. This means that the variable TennisPlayerName is not the
same as the variable tennisplayername.
Declaring Variables
Naming Variables in C#
2.4 Creating Objects ¤NIIT
You can declare and initialize variables by using the following syntax:
<data_type> <variable_name>=<value>;
In the preceding syntax, the <data_type> represents the kind of data type that will be
stored in a variable and
<value> specifies the value that needs to be stored in a variable.
Consider the following statement of variable declarations:
int age;
The preceding statement declares the variable age of the int data type and initializes the
variable with the value
0. The int data type is used to store numeric data.
Consider the following statement:
char choice=’y’;
The preceding statement declares the variable choice of the char data type and
initializes the variable with the value

y.
The data type represents the kind of data that will be stored in a variable.
C# provides various built-in data types. Built-in data types are the predefined data types.
The following table lists some of the built-in data types.
Predefined Type #Bytes Range of Values
char 2 0 and 65535
int 4 -2,147,483,648 and 2,147,483,647
float 4 -3.402823E+38 and -1.401298E-45 (For
negative values)
1.401298E-45 and 3.402823E+38 (For
positive values)
double 8 -1.79769313486232E308 to -
4.94065645841247E-324 (for negative
values) and 4.94065645841247E-324 to
1.79769313486232E308 (for positive values)
Data Types in C#
Declaring and Initializing Va
r
iables
¤NIIT Creating Objects 2.5
N
ote
Predefined Type #Bytes Range of Values
bool 1 True or False
string Variable
length
0-2 billion Unicode characters
Built-In Data Types
Built-in data types are represented at the machine level. The storage requirement,
therefore, depends on the hardware. The #Bytes column in the preceding table depicts the

bytes required to store the value in the memory.
C# also provides user-defined data types. You will learn about user-defined data types
in subsequent chapters.
Types of Data Types
C# supports two types of data types. The types of data types supported by C# are:
 Value types: They directly contain data. Some examples of the value types are
char, int, and float, which can be used for storing alphabets, integers, and
floating point numbers, respectively. When you declare an
int variable, the system
allocates memory to store the value. The following figure shows the memory
allocation of an int variable.


Memory Allocation in Value Type
Num
Memory allocated
Variable declared
int Num;
Num=5;
5
2.6 Creating Objects ¤NIIT

Reference types: The reference types do not maintain data but they contain a
reference to the variables, which are stored in memory. Using more than one
variable, you can use the reference types to refer to a memory location. This means
that if the value in the memory location is modified by one of the variables, the other
variables automatically reflect the changed value. The example of a reference type is
string data type.
The following figure shows the memory allocation of a
string value “HELLO” in a

variable named
Str.
Memory Allocation of the String Type Variable
In the preceding figure, the value of the variable Str is stored in memory and the
address of this memory is stored at another location.
To understand how to store value in a variable, consider the following code snippet:
int Number;
Number = Convert.ToInt32(Console.ReadLine());
In the preceding code snippet, the Console.ReadLine() is used to accept input from the
user and store it in the
Number variable. Console.ReadLine() is a function of the
Console class, which is a part of the System namespace.
The
Convert.ToInt32() converts the data entered by the user to the int data type. You
need to perform conversion because
Console.ReadLine() accepts the data in string
format. The
Convert class contains methods that explicitly tell the compiler to convert
one data type into another data type. This is called explicit conversion. The compiler
performs an implicit conversion automatically. For example, implicit conversion converts
the
int data type to float or float data type to int, automatically.
A
ccepting and Storing Values in Member Variables
Str
0 1 2 3 4
H E L L O
Address
¤NIIT Creating Objects 2.7
In this section you will learn to write, compile, and execute a C# program.

A C# program can be written by using Notepad. Consider the following code, which
declares the
Car class and creates the object MyCar of the same class:
using System;
class Car
{
//Member variables
string Engine;
int NoOfWheels;
//Member functions
public void AcceptDetails()
{
Console.WriteLine("Enter the Engine Model");
Engine = Console.ReadLine();
Console.WriteLine("Enter the number of Wheels");
NoOfWheels = Convert.ToInt32(Console.ReadLine());
}
public void DisplayDetails()
{
Console.WriteLine("The Engine Model is:{0}", Engine);
Console.WriteLine("The number of wheels are:{0}",
NoOfWheels);
}
}
//Class used to instantiate the Car class
class ExecuteClass
{
public static void Main(string[] args)
{
Car MyCar = new Car();

MyCar.AcceptDetails();
MyCar.DisplayDetails();
}
}
Writing and Executing a C# Program
Creating a Sample C# Program
2.8 Creating Objects ¤NIIT
The output of the preceding code is as follows.
Output of the Sample C# Program
The using Keyword
First statement in a typical C# program is:
using System;
The using keyword is used to include the namespaces in the program. Keywords are
reserved words that have a special meaning. The statement,
using System, declares that
you can refer to the classes defined in the namespace without using the fully qualified
name. A program can include multiple
using statements.
The class Keyword
The class keyword is used to declare a class. In the preceding code, the class keyword
defines the class
Car. The braces, known as delimiters, are used to indicate the start and
end of a class body.
¤NIIT Creating Objects 2.9
The Comment Entry
Comments are a part of the program and are used to explain code. Compilers ignore
comment entries. The following symbols are used to give a comment entry in C#:
// Comment Text
or
/* This is the sample program

to display addition of two numbers
Comment Text */
If a comment entry spans more than one line, it has to be enclosed within ‘/*’ and ‘*/’.
The symbol ‘
//’ treats the rest of code within the same line as a comment.
Member Variables
Variables are used to store data. Variables are also called the data members of a class. In
the preceding code, class
Car has two member variables called Engine and NoOfWheels.
These member variables can be used to store data for a car.
Member Functions
A function is a set of statements that performs a specific task in response to a message.
The functions of a class are called member functions in C#. Member functions are
declared inside the class. The function declaration introduces the function in the class and
the function definition contains the function code.
The preceding code contains two member functions named
AcceptDetails and
DisplayDetails. These are declared and defined inside the class. Notice, the function
definition contains code, which is enclosed in a block. The block is enclosed within
braces ‘
{}’.
Instantiating Class
In the preceding code, the ExecuteClass class is declared with the Main() method. The
ExecuteClass is used as a class from where the Car class can be instantiated. The first
line of code that a C# compiler looks for in the source file compiled is the
Main()
function.
2.10 Creating Objects ¤NIIT
To use a class the members of a class, you need to create an object of the class. Objects
interact with each other by passing messages and by responding to the received messages.

Objects use methods to pass messages. In C#, the task of passing messages can be
accomplished by using member functions.
All the objects of a class share the same copy of the member functions but they maintain a
separate copy of the member variables in memory. The sharing of member functions and
non sharing of member variables of classes and objects in shown in the following figure.
A Class and its Objects
Class
Member Variable1
Member Variable2
Member Function1
Member Function2
Member Variable1
Member Variable2
Object
Member Variable1
Member Variable2
Object
¤NIIT Creating Objects 2.11
N
ote
In the preceding code, you have declared a class named Car. To create an object named
MyCar of the type Car, the following code is given in the Main() method:
Car MyCar = new Car();
The member functions of the class are accessed through an object of the class by using the

.” operator, as shown in the following example:
MyCar.AcceptDetails();
MyCar.DisplayDetails();
In the preceding example, the object name and the “.” operator are used to access the
member function

AcceptDetails() and DisplayDetails(). This means that the object
MyCar of the class Car has invoked the function AcceptDetails() and
DisplayDetails(). This function accepts the values of engine type and the number of
wheels from the user and displays the same.
The preceding code invokes the member function, which is written within the Main()
function. Usually, member functions are declared and defined under the public access
specifier. Access specifiers are used to determine if any other class can access the variables
or function of a class.
After writing a C # program in Notepad, you need to compile and execute it to get the
desired output. The compiler converts the source code that you write in the machine code,
which the computer can understand.
Yon need to perform the following steps to compile and execute a C# program:
1. Save the code written in Notepad with an extension
.cs.
2. To compile the code, you need to go to the Visual Studio 2005 command prompt.
Select StartÆAll ProgramsÆVisual Studio 2005ÆVisual Studio ToolsÆVisual
Studio 2005 Command Prompt to compile this program.
3. In the Visual Studio 2005 Command Prompt window, move to the location where
the programs file is saved.
4. Compile the program file by using the following command:
csc ExecuteClass.cs
5. To execute the code, type the following on the command prompt:
ExecuteClass.exe
or ExecuteClass
Compiling and Executing C# Program
2.12 Creating Objects ¤NIIT
Problem Statement
David is the member of a team that is developing the Automatic Ranking software for a
tennis tournament. You have been assigned the task of creating a program. The program
should accept the following details of a tennis player and display it:

 Name, containing a maximum of 25 characters
 Rank as an integer
Help David to create the program.
Solution
To develop the required program, David needs to perform the following steps:
1. Select StartÆAll ProgramsÆAccessoriesÆNotepad.
2. Write the following program code in Notepad:
using System;
class TennisPlayer
{
string TennisPlayerName;
int Rank;
public void PrintPlayerDetails()
{
Console.WriteLine("The details of the Tennis Players are:
");
Console.WriteLine("Name: ");
Console.WriteLine(TennisPlayerName);
Console.WriteLine("Rank: ");
Console.WriteLine(Rank);
}
public void GetPlayerDetails ()
{
Console.WriteLine("Enter the details of the Tennis
Players ");
Console.WriteLine("\n Enter TennisPlayer Name: ");
TennisPlayerName=Console.ReadLine();
Console.WriteLine("Rank: ");
Rank=Convert.ToInt32(Console.ReadLine());
}

}
class Tennis
{
public static void Main(string[] args)
{
TennisPlayer P1=new TennisPlayer();
Activity: Creating a C# Program
¤NIIT Creating Objects 2.13
P1.GetPlayerDetails();
P1.PrintPlayerDetails();
}
}
3. Select FileÆSave to save the program file. The Save As dialog box opens.
4. Enter Tennis.cs in the File name text box. The filename is saved with .cs extension,
signifying that it is a C# program.
5. Select StartÆAll ProgramsÆVisual Studio 2005ÆVisual Studio ToolsÆVisual
Studio 2005 Command Prompt to compile this program.
6. In the Visual Studio 2005 Command Prompt window, move to the location where
the programs file is saved.
7. Compile the program file by using the following command:
csc Tennis.cs
8. Execute the compiled program as:
Tennis.exe
9. Verify the output of the executed program.
The output of the executed program is as follows.
Output of the C# Program
2.14 Creating Objects ¤NIIT
1. In the statement, using System, System is a _____________.
a. Namespace
b. Class

c. Object
d. Keyword
2. Which of the following is not an example of value type?
a.
char
b.
int
c.
float
d. string
3. The ________ compiler is used for C#.
a.
cc
b. csc
c.
c++
d.
cs
4. The statement // Hello world in a C# program:
a. Displays the text Hello world on the screen
b. Is not executed by the compiler and will be treated as a comment
c. Declares a variable Hello world
d. Causes all code lines following it to be treated as comments
5. In which of the following
datatype does the Console.Readline() function accept
a value?
a.
int
b. float
c.

bool
d. string
Practice Questions
¤NIIT Creating Objects 2.15
In this chapter, you learned that:
 A variable is a named location in the memory that contains a specific value.
 A data type defines the type of data that can be stored in a variable.
 The two types of data type are Value type and Reference type.
 The ReadLine() function is used to accept inputs from the user.
 The using keyword is used to include namespaces in a program.
 A namespace contains a set of related classes.
 Member variables are declared inside the class body.
 Comment entries are notes written by a programmer in code so that others reading
that code can understand it better.
 An object is an instance of a class.
 The compiler software translates a program written in a language, such as C#, into
the machine language.
Summary
2.16 Creating Objects ¤NIIT
Exercise 1
Diaz Entertainment, Inc. is developing a software application for toddlers that would
enable them to identify and distinguish shapes and colors. You have defined the
Geometrical_Shapes class as a part of developing the software. The following is the
class definition:
class Geometrical_Shapes
{
double No_of_coordinates;
double Area;
string Color;
public:

void Create()
{
//Code to accept the user inputs and store the values in
//the corresponding variables
}
void Display()
{
//Code to display the details of the shape such as
//no_of_coordinates, area, and color
}
}
The Geometrical_Shapes class definition contains errors and is incomplete. You need to
fix the errors and complete code in the
Geometrical_Shapes class definition. You also
need to write the
Main() function, compile, and execute the code.
Exercise 2
Jim is developing software for automating the slot booking process for a video game
parlor. Customers fill the Booking Request form with the details of the game, such as the
name, number of players, and complexity level. They hand over the form to the booking
officer at the parlor. Depending on the availability, the booking officer reserves the time
slots and the play station for customers.
Identify the involved classes and objects, and their attributes. Write methods in the class
to accept the game details and store the values in a variable.
Exercises
¤NIIT Creating Objects 2.17
Exercise 3
Predict the output of the following code:
using System;
class Myclass

{
static void Main()
{
string Answer="Y";
string Response_code="66";
int Counter=60;
Console.WriteLine(Answer);
Console.WriteLine(Response_code);
Console.WriteLine(Counter);
}
}
Exercise 4
An automobile company has developed an application for maintaining the number of
wheels in a vehicle. Predict the output of the following partial code of the application:
using System;
class Vehicle
{
public int Number_of_tyres;
}
class MyVehicle
{
static void Main(string[] args)
{
Vehicle Motorcycle= new Vehicle();
Vehicle Car = new Vehicle();
Console.WriteLine("Enter the number of wheels in a
car:");
Car.Number_of_tyres=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the number of wheels in a
Motorcycle:");

Motorcycle.Number_of_tyres=Convert.ToInt32
(Console.ReadLine());
Console.WriteLine("\n");
Console.WriteLine(Car.Number_of_tyres);
Console.WriteLine(" :is the number of wheels in a Car
\n");
Console.WriteLine(Motorcycle.Number_of_tyres);
Console.WriteLine(" :is the number of wheels in a
Motorcycle \n");
}
}
2.18 Creating Objects ¤NIIT
Exercise 5
TechnoSoft, a leading software company, has developed an application for maintaining
the scores of games in a video game parlor. If the New score is greater than the stored Top
score, the following program should interchange the values of the variables
Top_score
and New_score. However, the program does not generate the desired output. Identify the
error in the following program and write the correct code:
using System;
class Interchange
{
int Top_score;
int New_score;
int Temp;
void Swap()
{
Top_score=5;
New_score=10;
Temp=top_score;

New_score=Top_score;
Top_score=New_score;
}
void Display()
{
Console.WriteLine("The new value of top score is:");
Console.WriteLine(Top_score);
Console.WriteLine("The old value of top score was:");
Console.WriteLine(New_score);
}
static void Main()
{
Interchange I1;
I1.Swap();
I1.Display();
}
}
Exercise 6
As a part of the team that is developing software for a library, you have been assigned the
task of writing a program. The program should accept the following book details:
 ISBN Number
 Book Category (Fiction or Nonfiction)
 Author
 Number of copies available
Write a C# program to accept and display the preceding book details.

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×