Title: CS 112 Introduction to Programming
1CS 112 Introduction to Programming
- Lecture 15
- Defining Classes
- Http//zoo.cs.yale.edu/classes/cs112/
2Outline
- Admin. and review
- Classes and objects
- Defining classes
- Basic syntax
- Examples
3Admin.
- Assignment 3
- Due Oct. 13
- Two problems
- Problem 1 Control structure and method reuse
- Problem 2 Method decomposition
4Review Program Development Process
5Design
year GetYearFromUser()
month GetMonthFromUser()
month ? 0
t
f
PrintMonth(month, year)
PrintYear(year)
6Design PrintMonth( month, year )
Print month header
GetFirstWeekday (month, year)
IndentInitialWeekdays
GetMonthDays(month, year)
Print each day
7Methods To Be Implemented and an Order to
Implement them
- static string GetMonthName( int month )
- // The English word for a specific month
- static bool IsLeapYear( int month, int year )
- // Check if a year is a leap year
- static int GetMonthDays( int month, int year )
- // Calculate the number of days for a specific
month of a specific year - static int GetFirstWeekday( int month, int year
) - // Calculate the weekday of the first day of a
month (in a specific year) - static void IndentInitialWeekdays( int weekday )
- // Indent the first line so that the first
day appears in the correct position - static void PrintMonth( int month, int year )
- static void PrintYear( int month, int year )
- static void GievInstructions( int month, int year
) - static void GetYearFromUser( int month, int year
) - static void GetMonthFromUser( int month, int year
) - static void Main( string args )
8Example Implementing GetMonthName
- static string GetMonthName(int month)
-
- switch (month)
- case 1 return ("January")
- case 2 return ("February")
- case 3 return ("March")
- case 4 return ("April")
- case 5 return ("May")
- case 6 return ("June")
- case 7 return ("July")
- case 8 return ("August")
- case 9 return ("September")
- case 10 return ("October")
- case 11 return ("November")
- case 12 return ("December")
- default return ("Illegal month")
-
- // end of method GetMonthName
static void Main( string args )
Console.WriteLine( GetMonthName( 1 ) ) //
end of method Main
Test
9Example Implementing IsLeapYear
- static bool IsLeapYear(int year)
-
- return ( (year 4 0) (year 100 ! 0)
) -
- ( year 400 0)
- // end of method IsLeapYear
static void Main( string args )
Console.WriteLine( IsLeapYear( 2000 ) )
Console.WriteLine( IsLeapYear( 1900 ) )
Console.WriteLine( IsLeapYear( 2003 ) ) // end
of method Main
10Example Implementing GetMonthDays
- static int GetMonthDays(int month, int year)
-
- switch ( month )
-
- case 2
- return IsLeapYear( year ) ? 29 28
- case 4 case 6 case 9 case 11
- return (30)
- default
- return (31)
- // end of switch
- // end of method GetMonthDays
static void Main( string args )
Console.WriteLine( GetMonthDays( 2, 2000 ) )
Console.WriteLine( GetMonthDays( 2, 1900 ) )
Console.WriteLine( GetMonthDays( 6, 2003 )
) // end of method Main
11Summary Method Control Flow
PrintMonth
GetMonthDays
GetMonthDays()
12Summary
- Design
- Top-down stepwise refinement
- Implementation and testing
- Bottom-up
- Write the simple functions first
- Write a piece and test a piece
- Test a method
- using some dummy method calls, e.g.
- Call the method in Main() with some typical
test cases - using Visual Studio Immediate window
13Outline
- Admin. and review
- Classes and objects
- Defining a class
- Basic syntax
- Examples
14Object-Oriented Design
- The focus of methods is on doing things roughly
speaking, we can say that methods focus on the
verbs. - In object-oriented design, we focus on the nouns
- In object-oriented design, we tend to group
methods together according to the nouns - Important for large, complex programs
15C Classes
- A C class plays dual roles
- Program module containing a list of (static)
method declarations and (static) data fields - Blueprint for generating objects
- It is the model or pattern from which objects are
created - Supports two techniques which are essence of
object-oriented programming - data encapsulation (for abstraction)
- inheritance (for code reuse)
16User-Defined Class
- A user-defined class is also called a
user-defined type - class written by a programmer
- A class encapsulates (wrap together) data and
methods - data members (member variables or instance
variables) - methods that manipulate data members
17Objects
- An object has
- state - descriptive characteristics
- behaviors - what it can do (or be done to it)
- For example, consider a coin in a computer game
- The state of the coin is its current face (head
or tail) - The behavior of the coin is that it can be
flipped - Note the interactions between state and behaviors
- the behavior of an object might change its state
- the behavior of an object might depend on its
state
18Outline
- Admin. and review
- Classes and objects
- Defining a class
- Basic syntax
- Examples
19Defining Classes
- Use Project lt Add Class to add a new class to
your project - A class contains data declarations and method
declarations
Data declarations
Method declarations
Member (data/method) Access Modifiers public
member is accessible outside the class private
member is accessible only inside the class
definition
20Data Declarations
- You can define two types of variables in a class
but not in any method (called class variables) - static class variables
- nonstatic variables are called instance variables
(fields) because each instance (object) of the
class has its own copy - class variables can be accessed in all methods of
the class - Comparison Local variables
- Variables declared within a method or within a
block statement - Variables declared as local variables can only be
accessed in the method or the block where they
are declared
21Method Declarations
- A class can define many types of methods, e.g.,
- Access methods read or display data
- Predicate methods test the truth of conditions
- Constructors
- initialize objects of the class
- they have the same name as the class
- There may be more then one constructor per class
(overloaded constructors) - can take arguments
- they do not return any value
- it has no return type, not even void
22Outline
- Admin. and review
- Classes and objects
- Defining a class
- Basic syntax
- Examples
23Example Time1 class
- We define the Time1 class to represent time
midnight to 115959 - The state of a time object can be represented by
- hour, minute, second integers representing time
- We might define the following methods
- a Time1 constructor, to set up the object
- a SetTime method, to set time
- a ToUniversalString method, to convert the
internal representation to a string representing
the time in 24 hour format - a ToStandardString method, to convert the
internal representation to a string representing
the time in 12 hour format
24Time1.cs
- 1 // Fig. 8.1 Time1.cs
- 2 // Class Time1 maintains time in 24-hour
format. - 3
- 4 using System
- 5
- 6 // Time1 class definition
- 7 public class Time1
- 8
- 9 private int hour // 0-23
- 10 private int minute // 0-59
- 11 private int second // 0-59
- 12
- 13 // Time1 constructor initializes instance
variables to - 14 // zero to set default time to midnight
- 15 public Time1()
- 16
- 17 SetTime( 0, 0, 0 )
- 18
- 19
25Time1.cs
- 33 // convert time to universal-time (24
hour) format string - 34 public string ToUniversalString()
- 35
- 36 return String.Format(
- 37 "0D21D22D2", hour,
minute, second ) - 38
- 39
- 40 // convert time to standard-time (12
hour) format string - 41 public string ToStandardString()
- 42
- 43 return String.Format(
"01D22D2 3", - 44 ( ( hour 12 hour 0 ) ? 12
hour 12 ), - 45 minute, second, ( hour lt 12 ? "AM"
"PM" ) ) - 46
- 47
- 48 // end class Time1
26TimeTest1.cs
- 1 // Fig. 8.2 TimeTest1.cs
- 2 // Demonstrating class Time1.
- 3
- 4 using System
- 5 using System.Windows.Forms
- 6
- 7 // TimeTest1 uses creates and uses a Time1
object - 8 class TimeTest1
- 9
- 10 // main entry point for application
- 11 static void Main( string args )
- 12
- 13 Time1 timeObj1 new Time1() //
calls Time1 constructor - 14 string output
- 15
- 16 // assign string representation of
time to output - 17 output "Initial universal time is "
- 18 timeObj1.ToUniversalString()
- 19 "\nInitial standard time is
"
27TimeTest1.cs Program Output
- 34 output "\n\nAfter attempting
invalid settings " - 35 "\nUniversal time "
time.ToUniversalString() - 36 "\nStandard time "
time.ToStandardString() - 37
- 38 MessageBox.Show( output, "Testing
Class Time1" ) - 39
- 40 // end method Main
- 41
- 42 // end class TimeTest1
28Class View and Object Browser
- Class View and Object Browser are features of
Visual Studio that facilitate the design of
object-oriented applications - Class View
- Displays variables and methods for all classes in
a project - Displays as treeview hierarchical structure
- at nodes allows nodes to be expanded
- - at nodes allows nodes to be collapsed
- Can be seen by selecting View lt Class View
29Class View Example
Fig. 8.20 Class View of class Time1 (Fig. 8.1)
and class TimeTest1 (Fig. 8.2).
30Object Browser
- Object Browser
- Lists all classes in a library
- Helps developers learn about the functionality of
a specific class - To view the Object Browser select any .NET FCL
method, right click, and select Go To Definition
31Object Browser Example
Fig. 8.21 Object Browser when user selects
MessageBox from TimesTest1.cs.
32Example 2 The Coin Class
- We define a Coin class to model a coin in a game
- In our Coin class we could define the following
data - face, an integer that represents the current face
- HEADS and TAILS, integer constants that represent
the two possible states - We might also define the following methods
- a Coin constructor, to set up the object
- a Flip method, to flip the coin
- a GetFace method, to return the current face
- a StateToString method, to return a string
description of the current state - See Coin.cs, CountFlips.cs, FlipRace.cs
- To compile CountFlips csc CountFlips.cs
Coin.cs - To compile FlipRace csc FlipRace.cs Coin.cs
33Instance Data The Two Coins in FlipRace
34Backup Slides
35Summary Data Scope
- Variables declared in a larger scope can be
accessed in an enclosed scope, e.g. - Variables declared in a class can be accessed by
the methods in the class - Variables declared in a method can only be
accessed in the method - Variables declared in a block can only be
accessed in the block