1. Trang chủ
  2. » Công Nghệ Thông Tin

Creating Objects pot

18 77 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 18
Dung lượng 637,52 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

You can declare and initialize variables by using the following syntax: =; In the preceding syntax, the represents the kind of data type that will be stored in a variable and specifi

Trang 1

Creating Objects Ch

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

Trang 3

Note

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

Declaring Variables

Naming Variables in C#

Trang 4

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

float 4 -3.402823E+38 and -1.401298E-45 (For

negative values) 1.401298E-45 and 3.402823E+38 (For positive values)

-4.94065645841247E-324 (for negative values) and 4.94065645841247E-324 to 1.79769313486232E308 (for positive values)

Data Types in C#

Declaring and Initializing Variables

Trang 5

Note

Predefined Type #Bytes Range of Values

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

Num

Memory allocated Variable declared

int Num;

Trang 6

„ 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

Accepting and Storing Values in Member Variables

0 1 2 3 4

Address

Trang 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

Trang 8

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

Trang 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()

Trang 10

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

Trang 11

Note

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

Compiling and Executing C# Program

Trang 12

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

Trang 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

Trang 14

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

Trang 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

„ TheReadLine() function is used to accept inputs from the user

„ Theusing 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

Ngày đăng: 01/08/2014, 09:21