Advanced Programming Class & Objects. Example Create class account to save personal account for a...

51
Advanced Programming Class & Objects Class & Objects

Transcript of Advanced Programming Class & Objects. Example Create class account to save personal account for a...

Page 1: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Advanced Programming

Class & ObjectsClass & Objects

Page 2: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Example

• Create class account to save personal account for a

bank.

• The class has account# and balance data

• The class has deposit( ), withdraw( ) and

display_data( ) methods

• The main class create some account for some

persons (as input data)

Page 3: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

OO Programming Concepts

data field 1

method n

data field n

method 1

An object

...

...

State

Behavior

Data Fieldradius = 5

MethodfindArea

A Circle object

Page 4: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Class and Objects

Circle

radius

findArea

circle1: Circle

radius = 2

new Circle()

circlen: Circle

radius = 5

new Circle()

...

Graphicalnotation forclasses

Graphicalnotation forobjects

Page 5: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Object Oriented vs…?

• Object Oriented is in contrast to procedural programming• A class is data structure with methods• C – procedural because all

– functionality is grouped into functions– all data is isolated into primitive variables or into data

structures• VB.NET & C# & JAVA - object oriented because

– all data and related functions (& subs) are grouped together into class

– Has encapsulation, inheritance and polymorphism (the 3 requirements of OO)

Page 6: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Class Declaration

class Circle { double radius = 1.0;

double findArea() { return radius*radius*3.14159;

}}

Page 7: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Declaring/Creating Objectsin a Single Step

ClassName objectName = new ClassName();

Example:Circle myCircle = new Circle();

Page 8: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Accessing Objects

• Referencing the object’s data:

objectName.data

myCircle.radius

• Referencing the object’s method:

objectName.method

myCircle.findArea()

Page 9: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Object Oriented – Why?

• Allows for more efficient code reuse and design

• Easier to modify and add to later

• Helps separate presentation layer from business logic

layer from data layer

• OO is based on the key idea of objects, which can be

physical (car) or conceptual (bank account)

Page 10: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

2 Key Concepts

• A class and an Object

• A class is the blueprint, an object is the building.

• You can have multiple buildings from the same blue

print, with different furniture in each one (i.e.

different data values). You still only have 1 blueprint

• The blueprint itself can have certain features, these

are called Shared properties and methods. Request

and Response properties are all shared

Page 11: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

OO Definitions

• A Class

– The blueprint from which objects are made. Blueprints

can have properties and methods as well.

– The shape in the cookie cutter is the class and the

cookie is an object

– A class that inherits from another class is called a

derived class, and the one it inherited from is the parent

class

Page 12: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Class

• Object classes encapsulate (wrap together) data and methods

• Classes have

– Data members (member variable or instance variables)

– Methods that manipulate the data members

Page 13: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

OO Definitions

• Method

– A subroutine or function that is contained within a class. They may have a defined scope of access which is either

• Public – available to anyone who has access to the object

• Protected – available to anyone who inherits from the object but no one else

• Private – only available to other methods and properties of the class itself

• Friend – available to anyone who has access to the object and is in the same DLL (Advanced Feature)

Page 14: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

OO Definitions

• Property

– Provides the user of the class with a ‘variable’ to tell you

about or let you affect the state of the object

– Implemented with a Set and Get method within the class

but looks you are setting a variable on the class

• myAnswer.QuestionID = 7

• Is really (show the code!)

– Scope of access is the same as a method, i.e. Public,

Protected, Private or Friend

Page 15: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Example

• Write OOP program to include Employee class to store employee’s name, hourly rate, brith_date, start_date, and hours worked. Brith_year and start_year.

• Employee class has methods: initialize hourly rate to a minimum wage of $6.00 per hour and hours worked to 0 when employee object is defined

• Method to get employee’s name, hourly rate, and hours worked from user

• Method to return weekly pay including overtime pay where overtime is paid at rate of time-and-a-half for any hours worked over 40

• Method to display employee information including employee pay for given week

Page 16: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

16

Recap: Encapsulation and Public and Private Accessibility

violate

Encapsulation

Unless properties

enforce

encapsulation

provide services

to clients

support other

methods in the

class

public private

variables

methods

Page 17: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Constructors

Circle(double r) { radius = r;}

Circle() { radius = 1.0; }

myCircle = new Circle(5.0);

Page 18: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Example

• Write a 12-hour clock program that declares a clock class to store hours, minutes, seconds, A.M. and P.M. provide methods to perform the following tasks:– Set hours, minutes, seconds to 00:00:00 by default

– Initialize hours, minutes, seconds, A.M. and P.M. from user entries

– Allow the clock to tick by advancing the seconds by one and at the same time correcting the hours and minutes for a 12-hour clock value of AM or PM

– Display the time in hours:minutes:seconds AM / PM format

Page 19: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

19 using System; public class Time1 { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59// Set new time value.public void SetTime(int hourValue, int minuteValue, int secondValue ) {hour = ( hourValue >= 0 && hourValue < 24 ) ? hourValue : 0;minute = ( minuteValue >= 0 && minuteValue < 60 )? minuteValue : 0;second = ( secondValue >= 0 && secondValue < 60 )? secondValue : 0; }

Page 20: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

20

public string ToUniversalString()

{

return (“ “+hour+” “+minute+” “+ second) ;

}

// convert time to standard-time (12 hour) format string

public string ToStandardString()

{

return (“ “+( ( hour == 12 || hour == 0 ) ? 12 : hour %

12 )+ “ “+ minute+” “+second+” “+(hour < 12 ? "AM" :

"PM" ) );

}

} // end class Time1

Page 21: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

21

using System; using System.Windows.Forms;class TimeTest1{static void Main( string[] args ) { Time1 time = new Time1(); // calls Time1 constructor string output;

output = "Initial universal time is: " + time.ToUniversalString() + "\nInitial standard time is: " + time.ToStandardString(); time.SetTime( 13, 27, 6 );

output += "\n\nUniversal time after SetTime is: " + time.ToUniversalString() + "\nStandard time after SetTime is: " + time.ToStandardString(); time.SetTime( 99, 99, 99 );

Page 22: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

22

output += "\n\nAfter attempting invalid settings: " +"\nUniversal time: " + time.ToUniversalString()+ "\n Standard time: " + time.ToStandardString(); MessageBox.Show( output, "Testing Class Time1" ); } // end method Main } // end class TimeTest1

Page 23: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

23

With Constructor

Page 24: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

24

using System; public class Time2 { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 public Time2() { SetTime( 0, 0, 0 ); } public Time2( int hour ) { SetTime( hour, 0, 0 ); } public Time2( int hour, int minute ) { SetTime( hour, minute, 0 ); }

Page 25: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

25

public string ToStandardString() { return String.Format( "{0}:{1:D2}:{2:D2} {3}", ( ( hour == 12 || hour == 0 ) ? 12 : hour % 12 ), minute, second, ( hour < 12 ? "AM" : "PM" ) ); } } // end class Time2

Page 26: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

26

Main Class

Page 27: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

27

using System; using System.Windows.Forms; class TimeTest2 {static void Main( string[] args ) { Time2 time1, time2, time3, time4, time5, time6; time1 = new Time2(); // 00:00:00 time2 = new Time2( 2 ); // 02:00:00 time3 = new Time2( 21, 34 ); // 21:34:00 time4 = new Time2( 12, 25, 42 ); // 12:25:42 time5 = new Time2( 27, 74, 99 ); // 00:00:00 time6 = new Time2( time4 ); // 12:25:42String output = "Constructed with: " + "\ntime1: all arguments defaulted" + "\n\t" + time1.ToUniversalString() + "\n\t" + time1.ToStandardString();output += "\ntime2: hour specified; minute and " + "second defaulted" + "\n\t" + time2.ToUniversalString() + "\n\t" + time2.ToStandardString();output += "\ntime3: hour and minute specified; " + "second defaulted" + "\n\t" + time3.ToUniversalString() + "\n\t" + time3.ToStandardString();

Page 28: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

28

output += "\ntime4: hour, minute, and second specified" + "\n\t" + time4.ToUniversalString() + "\n\t" + time4.ToStandardString(); output += "\ntime5: all invalid values specified" + "\n\t" + time5.ToUniversalString() + "\n\t" + time5.ToStandardString(); output += "\ntime6: Time2 object time4 specified" + "\n\t" + time6.ToUniversalString() + "\n\t" + time6.ToStandardString(); MessageBox.Show( output, "Demonstrating Overloaded Constructors" ); } // end method Main } // end class TimeTest2

Page 29: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Using the this reference

• Every object can reference itself by using the

keyword this

• Often used to distinguish between a method’s

variables and the instance variables of an object

Page 30: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

30

using System; public class Time4 { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 public Time4( int hour, int minute, int second ) { this.hour = hour; this.minute = minute; this.second = second; }public string BuildString() { return "this.ToStandardString(): " + this.ToStandardString() + "\nToStandardString(): " + ToStandardString(); }

Page 31: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

31

public string ToStandardString() { return String.Format( "{0}:{1:D2}:{2:D2} {3}", ( ( this.hour == 12 || this.hour == 0 ) ? 12 : this.hour % 12 ), this.minute, this.second, ( this.hour < 12 ? "AM" : "PM" ) ); } } // end class Time4

Page 32: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

32

using System; using System.Windows.Forms; class Class1 { static void Main( string[] args ) { Time4 time = new Time4( 12, 30, 19 ); MessageBox.Show( time.BuildString(), "Demonstrating the \"this\" Reference" ); } }

Page 33: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Example

• Write OOP program to include Employee class to store employee’s name, hourly rate, brith_date, start_date, and hours worked. Brith_date and start_date are object of Date class (day, month, year).

• Employee class has methods: initialize hourly rate to a minimum wage of $6.00 per hour and hours worked to 0 when employee object is defined

• Method to get employee’s name, hourly rate, and hours worked from user

• Method to return weekly pay including overtime pay where overtime is paid at rate of time-and-a-half for any hours worked over 40

• Method to display employee information including employee pay for given week

Page 34: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Example

Coffee shop need a program to computerize its inventory. The data will be Coffee name, price, amount in stock, sell by date.

The shop has two classes :coffee and batch. Coffee object can call operations (methods) in batch but not vice versa.

The operations on coffee are: prepare to enter stock, Display coffee data, change price, add stock (add new batch), sell coffee.

The operations on batches are: add new batch, display data about batch, and check how much is available.

Page 35: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Properties

• Public properties allow clients to:– Get (obtain the values of) private data

– Set (assign values to) private data

• Get accessor– Controls formatting of data

• Set accessor– Ensure that the new value is appropriate for the data member

Page 36: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Properties

• Typical pattern for accessing fields.private int x;public int GetX();public void SetX(int newVal);

• Elevated into the language:private int count;public int Count { get { return count; } set { count = value; }}

• Typically there is a backing-store, but not always.

Page 37: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Properties

• Using a property is more like using a public field than calling a function:FooClass foo;

int count = foo.Count; // calls get

int count = foo.count; // compile error

• The compiler automatically generates the routine or in-lines the code.

Page 38: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

381 // Fig. 8.6: Time3.cs2 // Class Time2 provides overloaded constructors.3 4 using System;5 6 // Time3 class definition7 public class Time38 {9 private int hour; // 0-2310 private int minute; // 0-5911 private int second; // 0-5912 13 // Time3 constructor initializes instance variables to 14 // zero to set default time to midnight15 public Time3()16 {17 SetTime( 0, 0, 0 );18 }19 20 // Time3 constructor: hour supplied, minute and second21 // defaulted to 022 public Time3( int hour ) 23 { 24 SetTime( hour, 0, 0 ); 25 }26 27 // Time3 constructor: hour and minute supplied, second28 // defaulted to 029 public Time3( int hour, int minute ) 30 { 31 SetTime( hour, minute, 0 );32 }33

Page 39: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

3934 // Time3 constructor: hour, minute and second supplied35 public Time3( int hour, int minute, int second ) 36 { 37 SetTime( hour, minute, second ); 38 }39 40 // Time3 constructor: initialize using another Time3 object41 public Time3( Time3 time )42 {43 SetTime( time.Hour, time.Minute, time.Second );44 }45 46 // Set new time value in 24-hour format. Perform validity47 // checks on the data. Set invalid values to zero.48 public void SetTime( 49 int hourValue, int minuteValue, int secondValue )50 {51 Hour = hourValue; 52 Minute = minuteValue;53 Second = secondValue;54 }55 56 // property Hour57 public int Hour58 {59 get60 {61 return hour;62 }63 64 set65 {66 hour = ( ( value >= 0 && value < 24 ) ? value : 0 );67 }68

Page 40: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

4069 } // end property Hour70 71 // property Minute72 public int Minute73 {74 get75 {76 return minute;77 }78 79 set80 {81 minute = ( ( value >= 0 && value < 60 ) ? value : 0 );82 }83 84 } // end property Minute85 86 // property Second87 public int Second88 {89 get90 {91 return second;92 }93 94 set95 {96 second = ( ( value >= 0 && value < 60 ) ? value : 0 );97 }98 99 } // end property Second100

Page 41: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

41101 // convert time to universal-time (24 hour) format string102 public string ToUniversalString()103 {104 return String.Format( 105 "{0:D2}:{1:D2}:{2:D2}", Hour, Minute, Second );106 }107 108 // convert time to standard-time (12 hour) format string109 public string ToStandardString()110 {111 return String.Format( "{0}:{1:D2}:{2:D2} {3}",112 ( ( Hour == 12 || Hour == 0 ) ? 12 : Hour % 12 ),113 Minute, Second, ( Hour < 12 ? "AM" : "PM" ) );114 } 115 116 } // end class Time3

Page 42: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

42

const and readonly Members

• Declare constant members (members whose value

will never change) using the keyword const

• const members are implicitly static

• const members must be initialized when they are

declared

• Use keyword readonly to declare members who

will be initialized in the constructor but not

change after that

Page 43: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

43

using System; using System.Windows.Forms; public class Constants { public const double PI = 3.14159; public readonly int radius; public Constants( int radiusValue ) { radius = radiusValue; } } // end class Constants public class UsingConstAndReadOnly { static void Main( string[] args ) { Random random = new Random(); Constants constantValues = new Constants( random.Next( 1, 20 ) );

Page 44: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

44

MessageBox.Show( "Radius = " + constantValues.radius + "\nCircumference = " + 2 * Constants.PI * constantValues.radius, "Circumference" ); } // end method Main }

Page 45: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

45

Example

– Define a person class with members: ID, name,

address, and telephone number. The class methods are

change_data( ), get_data( ), and display_data( ).

– Declare objects table with size N and provide the user

to fill the table with data.

– Allow the user to enter certain ID for the Main class to

display the corresponding person's name, address, and

telephone number.

Page 46: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

A chess club wants to make the rating list of the members of the club. When two members play a game, when a member plays with someone not belonging to club, his/her rating does not change: The rating of a new player is always 1000. When a player wins, his/her rating is increased by 10 points. When a player loses, his/her rating is decreased by 10 points. If a game is a draw (neither of the players wins), the rating of the player having originally higher rating is decreased by 5 points and the rating of the player having originally lower rating is increased by 5 points. If the ratings of the players are originally equal, they are not changed. The rating can never be negative. If the rating would become negative according to the rules above, it is changed to 0. Write a class Chessplayer that have instance variables name (String), count (int) and rating (int). The variable count is used to save the number of the games the player has played with other members of the club. A new player has a count value 0. Write a constructor to create a new player and the following methods (the headers of the methods show the purpose and parameters of the methods): String returnName(), void changeName(String newName), int returnCount(), void setCount(int newCount), int returnRating(), void setRating(int newRating), String toString() to help to output information about players, void game(Chessplayer anotherPlayer, int result). The method game changes the ratings and counts of both players according to the rules given above. The second parameter of the method tells the result of the game. If the parameter has value -1, anotherPlayer has won, if the parameter has value 1, anotherPlayer has lost, if the parameter has value 0, the game was a draw.

Page 47: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Write a class WaterTank to describe water tanks. Each water tank can contain a certain amount of water which has a certain temperature. The temperature must be more than 0, but less than 100. The class have variables volume (double) the volume of the tank, temperature (double) the temperature of the water in tank, and quantity (double) the quantity of water in tank. Write a constructor which has three parameters: the volume of the water tank to be created, the amount of water in it and the temperature of the water. (If the amount of the water is greater than the volume, the quantity of water is set to the volume of the tank. If the temperature is not in the given bounds, the temperature is set to 20) Write also the following methods:

double getQuantity() returns the amount of water in the tank

void setTemperature(double newTemperature) changes the temperature of water according to the parameter. If the parameter is not between 0 and 100, the temperature is not changed.

double transferWater(WaterTank anotherTank) transfers as much water as possible from the tank given as the first parameter to this tank. (The limit is either the amount of water in the other tank or the space available in this tank.) The method changes the values of the variables quantity and temperature of this tank and the value of variable quantity of the other tank. The return value of the method tells the amount of water transferred.

String toString() returns a string containing information of this tank.

Use the following expression to calculate the new temperature of water after some water has been added: if V1 liters of water having temperature T1 (in Centigrades) is combined with V2 liters of water having temperature T2, the temperature of the water after that is about (V1*T1 + V2*T2) / (V1 + V2). In addition, write a main program which creates three water tanks, changes the temperature of water in one of them, and transfers water from one tank to another tank. In the end, the program outputs information about all tanks.

Page 48: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Example

• Construct C# console application to store information about vehicle. A vehicle registration happens in a county, and involves a particular vehicle and its owners. You may assume that there is only one owner per vehicle. Each vehicle maps to a vehicle description that includes its make, model, year, and manufacturer. A registration can be renewed multiple times for the same owner and vehicle. The vehicle registration system is to be designed for quick retrieval of information about any vehicle or any vehicle owner and the related registration details.

Page 49: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Projects

• Can be a Windows App, Web App, or Web Service

• Group of 2-4 and design and implement own project in C#.

• Examples from past years include games, IM clients, and other applications.

• Groups will write a small proposal/specification of their project, implement it, and present their projects to the class on the last day of lecture.

Page 50: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.
Page 51: Advanced Programming Class & Objects. Example Create class account to save personal account for a bank. The class has account# and balance data The class.

Project

•  The App must show OOP and C# features use• Inheritance must be used