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

Creating Objects pot

18 77 0

Đ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

Nội dung

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 [...]... execute the code, type the following on the command prompt: ExecuteClass.exe NIIT or ExecuteClass Creating Objects 2.11 Activity: Creating a C# Program 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... 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 2.16 Creating Objects NIIT Exercise 3 Predict the output of the following code: using System; class Myclass { static void Main() { string Answer="Y";... following command: csc Tennis.cs 8 Execute the compiled program as: 9 Verify the output of the executed program Tennis.exe The output of the executed program is as follows Output of the C# Program NIIT Creating Objects 2.13 Practice Questions 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... 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 2.14 Creating Objects NIIT Summary 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... 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 NIIT Creating Objects 2.15 Exercises 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... TennisPlayerName=Console.ReadLine(); Console.WriteLine("Rank: "); Rank=Convert.ToInt32(Console.ReadLine()); } } class Tennis { public static void Main(string[] args) { TennisPlayer P1=new TennisPlayer(); 2.12 Creating Objects NIIT } 3 4 5 6 7 } P1.GetPlayerDetails(); P1.PrintPlayerDetails(); Select File Save to save the program file The Save As dialog box opens Enter Tennis.cs in the File name text box The filename... 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"); } } NIIT Creating Objects 2.17 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... 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 2.18 Creating Objects NIIT . Creating Objects Chapter 2 An object is an instance of a class. You create objects to access member variables and member functions. 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. 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

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