csci 3328 object oriented programming in c# chapter 3: introduction to classes and objects utpa –...

29
CSCI 3328 Object CSCI 3328 Object Oriented Programming in Oriented Programming in C# C# Chapter 3: Introduction Chapter 3: Introduction to Classes and Objects to Classes and Objects UTPA – Fall 2012 1

Upload: cora-briggs

Post on 12-Jan-2016

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

CSCI 3328 Object Oriented CSCI 3328 Object Oriented Programming in C# Programming in C#

Chapter 3: Introduction to Classes Chapter 3: Introduction to Classes and Objects and Objects

UTPA – Fall 2012

1

Page 2: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Objectives

• In this chapter, you will– Become aware of reasons for using objects and

classes

– Become familiar with classes and objects

2

Page 3: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

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

Page 4: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

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

Page 5: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

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

Page 6: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Objects

• Objects are packages that contain data and functions (methods) that can be performed on the data

6

Page 7: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

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

Page 8: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

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

Page 9: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Main Method

• Starting point of every application

• Console class has many methods including read and write–When using keyboard for input use ReadLine()

• You are going to use the Convert class all the time– Get to know this class well

9

Page 10: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Console.Write and WriteLine

• Console.WriteLine(“{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

Page 11: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Addition Programusing System;public class Addition{

public static void Main( string[] args ) {

int number1; // declare first number to add int number2; // declare second number to add int sum; // declare sum of number1 and number2

Console.Write( "Enter first integer: " ); // prompt user number1 = Convert.ToInt32( Console.ReadLine() ); Console.Write( "Enter second integer: " ); // prompt user number2 = Convert.ToInt32( Console.ReadLine() );

sum = number1 + number2; // add numbers

Console.WriteLine( "Sum is {0}", sum ); // display sum } // end of function Main

} // end of class Addition

11

Page 12: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Arithmetic Operators

• Unary: +, -

• Multiplicative: *, /, %

• Additive: +, -

• Relational operators– > < >= <=

• Equality operators– ==, !=

• Precedence of operators• http://msdn.microsoft.com/en-us/library/6a71f45d.aspx

12

high

low

Page 13: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

If Statementusing System;public class Comparison{ public static void Main( string[] args ) { int number1; // declare first number to compare int number2; // declare second number to compare Console.Write( "Enter first integer: " ); number1 = Convert.ToInt32( Console.ReadLine() ); Console.Write( "Enter second integer: " ); number2 = Convert.ToInt32( Console.ReadLine() );

if ( number1 == number2 ) Console.WriteLine( "{0} == {1}", number1, number2 ); if ( number1 != number2 ) Console.WriteLine( "{0} != {1}", number1, number2 ); if ( number1 < number2 ) Console.WriteLine( "{0} < {1}", number1, number2 ); if ( number1 > number2 ) Console.WriteLine( "{0} > {1}", number1, number2 ); if ( number1 <= number2 ) Console.WriteLine( "{0} <= {1}", number1, number2 ); if ( number1 >= number2 ) Console.WriteLine( "{0} >= {1}", number1, number2 ); } // end Main

13

Page 14: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

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

Page 15: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Example of a Class Declarationusing System;

public class GradeBook{ private string courseName; // course name for this GradeBook public string CourseName // property { get { return courseName; } // end get set { courseName = value;} // end set } // end property CourseName public void DisplayMessage() { // use property CourseName to get the // name of the course that this GradeBook represents Console.WriteLine( "Welcome to the grade book for\n{0}!", CourseName );

// display property CourseName } // end method DisplayMessage} // end class GradeBook

• See next slide how to use this class15

Page 16: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Using the Class GradeBookusing System;

public class GradeBookTest{ public static void Main( string[] args ) { GradeBook myGradeBook = new GradeBook(); //object created Console.WriteLine( "Initial course name is: '{0}'\n", myGradeBook.CourseName ); Console.WriteLine( "Please enter the course name:" ); myGradeBook.CourseName = Console.ReadLine(); // set Console.WriteLine(); // output a blank line myGradeBook.DisplayMessage(); } // end Main} // end class GradeBookTest

16

Page 17: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

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 courseName instance and public CourseName 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 CourseName {get;set;}

– You can assign values like:

myGradeBook.CourseName = Console.ReadLine();

17

Page 18: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Value Types vs. Reference Types

• Reference type contains the address of the location in memory where the data resides (refer to an object)

18

Page 19: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

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

Page 20: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

GradeBook Class With a Constructorusing System;public class GradeBook{

public string CourseName { get; set; }public GradeBook( string name ) //constructor{ CourseName = name; // set CourseName to name} // end constructor

public void DisplayMessage(){ Console.WriteLine( "Welcome to the grade book for\n{0}!", CourseName);

} // end method DisplayMessage} // end class GradeBook

20

Page 21: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Test the Class

using System;public class GradeBookTest{ public static void Main( string[] args ) { GradeBook gradeBook1 = new GradeBook("CS101 Introduction to C#

Programming" ); // invokes constructor GradeBook gradeBook2 = new GradeBook("CS102 Data Structures in

C#"); // invokes constructor Console.WriteLine( "gradeBook1 course name is: {0}", gradeBook1.CourseName ); Console.WriteLine( "gradeBook2 course name is: {0}", gradeBook2.CourseName ); } // end Main} // end class GradeBookTest

21

Page 22: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

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 65535bool 8 true, falseenum types and struct types

• Reference types include class types, interface types, delegate types, and array types

• Pointer types

22

Page 23: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

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.33M, it will be treated as a decimal number• M stands for money

23

Page 24: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Example of Decimal Number

class Program{ static void Main(string[] args) { decimal x = 3M; Console.WriteLine("{0:C}", x); Console.ReadLine(); }}

24

string format specifier

Page 25: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

String Format Specifiers

• C or c – Currency

• D or d – decimal

• X or x – hexadecimal

• E or e – scientific notion

25

Page 26: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Bank Account Examplepublic class Account{ private decimal balance; // instance variable that stores the balance public Account( decimal initialBalance ) // constructor {

Balance = initialBalance; // 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

Page 27: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Create and Manipulate an Accountusing System;public class AccountTest{ public static void Main( string[] args ) {

Account account1 = new Account( 50.00M ); // create Account objectAccount account2 = new Account( -7.53M ); // create Account objectConsole.WriteLine( "account1 balance: {0:C}", account1.Balance );

// display initial balance of each object using a propertyConsole.WriteLine( "account2 balance: {0:C}\n", account2.Balance ); // display Balance propertydecimal depositAmount; // deposit amount read from userConsole.Write( "Enter deposit amount for account1: " ); // prompt and obtain user inputdepositAmount = Convert.ToDecimal( Console.ReadLine() );Console.WriteLine( "adding {0:C} to account1 balance\n", depositAmount );

account1.Credit( depositAmount ); // add to account1 balanceConsole.WriteLine( "account1 balance: {0:C}", account1.Balance ); // display balancesConsole.WriteLine( "account2 balance: {0:C}\n", account2.Balance );Console.Write( "Enter deposit amount for account2: " );depositAmount = Convert.ToDecimal( Console.ReadLine() );Console.WriteLine( "adding {0:C} to account2 balance\n", depositAmount );account2.Credit( depositAmount ); // add to account2 balanceConsole.WriteLine( "account1 balance: {0:C}", account1.Balance );Console.WriteLine( "account2 balance: {0:C}", account2.Balance );

} // end Main} // end class AccountTest 27

Page 28: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

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

Page 29: CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall 2012 1

Summary

• Class– Constructor

– Destructor

– Fields

– Properties

– Methods (events)

• Resources: http://msdn.microsoft.com/en-us/library/0b0thckt(v=vs.80).aspx

29