CSCI 3328 Object Oriented Programming in C Chapter
CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects Xiang Lian The University of Texas – Pan American Edinburg, TX 78539 lianx@utpa. edu 1
Objectives • In this chapter, you will – Become aware of reasons for using objects and classes – Become familiar with classes and objects 2
Introduction • The book uses car analogy • We humans are very good in recognizing and working with objects, such as a pen, a dog, or a human being • We learned to categorize them in such a way that make sense to us. We may categorize them as animate object, inanimate objects, pets, friends, etc. 3
Introduction (cont'd) • We some times classify objects based on their attributes, for example, green apples or red apples, fat or slim people, etc. • If you think about it each object has many attributes. If I ask you list the attributes of an orange, you probably could list many things such as color, shape, weight, smell, etc. 4
Introduction (cont'd) • In addition to attributes, all objects exhibit behaviors • A dog eats, barks, wags its tail, plays, and begs – A dog exhibits many more other behaviors than this short list • Another thing we need to remember about objects is that objects interact between each other 5
Objects • Objects are packages that contain data and functions (methods) that can be performed on the data 6
Objects (cont'd) • Data could be considered to be attributes and functions are considered to be behaviors of the object • We can say that the attributes and behaviors are encapsulated into an object 7
Objects (cont'd) • The objects interact between each other through their interfaces • As an example a date object may have a set of data consisting of month, day and year, and methods consisting of assign date, display date, yesterday and tomorrow 8
Main Method • Starting point of every application • Console class has many methods including read and write – When using keyboard for input use Read. Line() • You are going to use the Convert class all the time – Get to know this class well 9
Console. Write and Write. Line • Console. Write. Line(“{0}n{1}”, “Welcome to”, “C# Programming!”); • Format items are enclosed in curly braces and contain a sequence of characters that tell the method which argument to use and how to format it. – Here, there are two arguments named {0} and {1} – The first argument will be followed by a new line character: n 10
Addition Program using System; public class Addition { public static void Main( string[] args ) { int number 1; // declare first number to add int number 2; // declare second number to add int sum; // declare sum of number 1 and number 2 Console. Write( "Enter first integer: " ); // prompt user number 1 = Convert. To. Int 32( Console. Read. Line() ); Console. Write( "Enter second integer: " ); // prompt user number 2 = Convert. To. Int 32( Console. Read. Line() ); sum = number 1 + number 2; } Console. Write. Line( "Sum is {0}", sum ); } // end of function Main // end of class Addition // add numbers // display sum 11
Arithmetic Operators • • Unary: +, Multiplicative: *, /, % Additive: +, Relational operators high – > < >= <= • Equality operators – ==, != • Precedence of operators low • http: //msdn. microsoft. com/en-us/library/6 a 71 f 45 d. aspx 12
If Statement using System; public class Comparison { public static void Main( string[] args ) { int number 1; // declare first number to compare int number 2; // declare second number to compare Console. Write( "Enter first integer: " ); number 1 = Convert. To. Int 32( Console. Read. Line() ); Console. Write( "Enter second integer: " ); number 2 = Convert. To. Int 32( Console. Read. Line() ); if ( number 1 == number 2 ) Console. Write. Line( "{0} == {1}", number 1, number 2 ); if ( number 1 != number 2 ) Console. Write. Line( "{0} != {1}", number 1, number 2 ); if ( number 1 < number 2 ) Console. Write. Line( "{0} < {1}", number 1, number 2 ); if ( number 1 > number 2 ) Console. Write. Line( "{0} > {1}", number 1, number 2 ); if ( number 1 <= number 2 ) Console. Write. Line( "{0} <= {1}", number 1, number 2 ); if ( number 1 >= number 2 ) Console. Write. Line( "{0} >= {1}", number 1, number 2 ); } // end Main 13
A Class is Like a Type • You cannot use a class until an instance (an object) of it is made • A class has properties (attributes) and methods – You can set and get the properties – Attributes are specified by the class’s instance variable – You can perform operations using methods 14
Example of a Class Declaration using System; public class Grade. Book { private string course. Name; // course name for this Grade. Book public string Course. Name // property { get { return course. Name; } // end get set { course. Name = value; } // end set } // end property Course. Name public void Display. Message() { // use property Course. Name to get the // name of the course that this Grade. Book represents Console. Write. Line( "Welcome to the grade book forn{0}!", Course. Name ); // display property Course. Name } // end method Display. Message } // end class Grade. Book • See next slide how to use this class 15
Using the Class Grade. Book using System; public class Grade. Book. Test { public static void Main( string[] args ) { Grade. Book my. Grade. Book = new Grade. Book(); //object created Console. Write. Line( "Initial course name is: '{0}'n", my. Grade. Book. Course. Name ); Console. Write. Line( "Please enter the course name: " ); my. Grade. Book. Course. Name = Console. Read. Line(); // set Console. Write. Line(); // output a blank line my. Grade. Book. Display. Message(); } // end Main } // end class Grade. Book. Test 16
Setting and Getting Values for Instance Variables • Controlled ways of allowing users to access variables • Usually get and set are made public so others can access them • Private course. Name instance and public Course. Name property • Note the uppercase/lowercase difference • Properties contain accessors that handle the details of returning and modifying data • After defining the property you can just use = to set it or get it by referring to it such as in read. • C# auto implements get/set for private instance variables. Example: • public string Course. Name {get; set; } – You can assign values like: my. Grade. Book. Course. Name = Console. Read. Line(); 17
Value Types vs. Reference Types • Reference type contains the address of the location in memory where the data resides (refer to an object) 18
Initializing Objects with Constructors • By default, when an object is created, it is initialized to null by default • If we rather have a different value initially, we can use constructors – The “new” operator automatically calls the constructor – See the next two slides for example 19
Grade. Book Class With a Constructor using System; public class Grade. Book { public string Course. Name { get; set; } public Grade. Book( string name ) //constructor { Course. Name = name; // set Course. Name to name } // end constructor public void Display. Message() { Console. Write. Line( "Welcome to the grade book forn{0}!", Course. Name); } // end method Display. Message } // end class Grade. Book 20
Test the Class using System; public class Grade. Book. Test { public static void Main( string[] args ) { Grade. Book grade. Book 1 = new Grade. Book("CS 101 Introduction to C# Programming" ); // invokes constructor Grade. Book grade. Book 2 = new Grade. Book("CS 102 Data Structures in C#"); // invokes constructor Console. Write. Line( "grade. Book 1 course name is: {0}", grade. Book 1. Course. Name ); Console. Write. Line( "grade. Book 2 course name is: {0}", grade. Book 2. Course. Name ); } // end Main } // end class Grade. Book. Test 21
About Some Data Types in C# • Value Types Size (in bits) Range sbyte 8 128 to 127 byte 8 0 to 255 short 16 -32768 to 32767 ushort 16 0 to 65535 int 32 147483648 to 2147483647 uint 32 0 to 4294967295 long 64 -9223372036854775808 to 9223372036854775807 ulong 64 0 to 18446744073709551615 char 16 0 to 65535 bool 8 true, false enum types and struct types • Reference types include class types, interface types, delegate types, and array types • Pointer types 22
Floating-Point Numbers and Decimal • Real numbers can be stored as float, double and decimal • In C#, float and double are treated as double by default • Float and double stores approximation of real numbers in available spaces • Decimal only stores limited range of decimal points precisely • Single precision floating point numbers have seven significant digits, whereas the double gives 15 to 16 significant digits • If you indicate a real number with M such as 18. 33 M, it will be treated as a decimal number • M stands for money 23
Example of Decimal Number class Program { static void Main(string[] args) string format specifier { decimal x = 3 M; Console. Write. Line("{0: C}", x); Console. Read. Line(); } } 24
String Format Specifiers • • C or c – Currency D or d – decimal X or x – hexadecimal E or e – scientific notion 25
Bank Account Example public class Account { private decimal balance; // instance variable that stores the balance public Account( decimal initial. Balance ) // constructor { Balance = initial. Balance; // set balance using property } // end Account constructor public void Credit( decimal amount ) // credit (add) an amount to the account { Balance = Balance + amount; // add amount to balance } // end method Credit public decimal Balance // a property to get and set the account balance { get {return balance; } // end get set {if ( value >= 0 ) balance = value; } // end set // validate that value is greater than or equal to 0; } } // end class Account 26
Create and Manipulate an Account using System; public class Account. Test { public static void Main( string[] args ) { Account account 1 = new Account( 50. 00 M ); // create Account object Account account 2 = new Account( -7. 53 M ); // create Account object Console. Write. Line( "account 1 balance: {0: C}", account 1. Balance ); // display initial balance of each object using a property Console. Write. Line( "account 2 balance: {0: C}n", account 2. Balance ); // display Balance property decimal deposit. Amount; // deposit amount read from user Console. Write( "Enter deposit amount for account 1: " ); // prompt and obtain user input deposit. Amount = Convert. To. Decimal( Console. Read. Line() ); Console. Write. Line( "adding {0: C} to account 1 balancen", deposit. Amount ); account 1. Credit( deposit. Amount ); // add to account 1 balance Console. Write. Line( "account 1 balance: {0: C}", account 1. Balance ); // display balances Console. Write. Line( "account 2 balance: {0: C}n", account 2. Balance ); Console. Write( "Enter deposit amount for account 2: " ); deposit. Amount = Convert. To. Decimal( Console. Read. Line() ); Console. Write. Line( "adding {0: C} to account 2 balancen", deposit. Amount ); account 2. Credit( deposit. Amount ); // add to account 2 balance Console. Write. Line( "account 1 balance: {0: C}", account 1. Balance ); Console. Write. Line( "account 2 balance: {0: C}", account 2. Balance ); } // end Main } // end class Account. Test 27
Your Second Assignment • Write a program to calculate an estimate on a paint job. User will enter Price of paint per gallon, and length and height of each wall. Amount of paint needed will be calculated from sqft as well as labor cost. • Create and use classes. 28
Summary • Class – Constructor – Destructor – Fields – Properties – Methods (events) • Resources: http: //msdn. microsoft. com/enus/library/0 b 0 thckt(v=vs. 80). aspx 29
- Slides: 29