CSE 210 Programming With Classes
CSE 210 Programming With Classes
Programming
with classes
Contents
Chapter 1 Introduction.........................................................................7
1.1 Version control.............................................................................7
1.1.1 What is version control?........................................................7
1.1.2 Files and folders....................................................................8
1.1.3 The file system......................................................................9
1.1.3.1 Moving around in the file system..................................10
1.1.3.2 Accessing files and folder.............................................11
1.1.4 Using git..............................................................................12
1.1.5 Create a new repository......................................................12
1.1.6 Clone the repository............................................................13
1.1.7 Making changes..................................................................13
1.1.7.1 Adding files...................................................................14
1.1.7.2 Commiting files.............................................................14
1.1.7.3 Pushing your changes to GitHub...................................15
1.1.7.4 Checking the status of your repo..................................15
1.1.8 A typical workflow...............................................................16
1.1.9 Assignment instructions......................................................16
1.2 Prove: Articulate – Version control.............................................16
1.3 Prove: Developer – C# Programming........................................17
1.3.1 C# Prep 1 – Variables, Input, and Output............................17
1.3.1.1 C# Language Fundamentals.........................................17
1.3.2 C# Prep 2 – Conditionals.....................................................22
1.3.2.1 Conditionals..................................................................23
1.3.2.1.1 If statements...........................................................23
1.3.2.1.2 Else and else if........................................................23
1.3.2.1.3 Operators................................................................24
1.3.2.1.4 And, Or, and Not Operators....................................25
1.3.2.2 Variables and types.......................................................25
1.3.2.2.1 Converting types....................................................25
1.3.2.3 Numbers to strings........................................................26
1.3.2.4 Assignment Instructions................................................26
1.3.3 C# Prep 3 – Loops...............................................................28
1.3.3.1 Loops.............................................................................28
1.3.3.1.1 While loops.............................................................28
1.3.3.1.2 Do-While loops........................................................28
1.3.3.1.3 For loops.................................................................29
1.3.3.1.4 Foreach loops..........................................................29
1.3.3.2 Random numbers..........................................................30
1.3.3.3 Assigment instructions..................................................30
1.3.4 C# Prep 4 – Lists.................................................................32
1.3.4.1 Collections....................................................................32
1.3.4.1.1 Lists........................................................................32
1.3.4.2 Adding items to the list.................................................33
1.3.4.2.1 Getting the list size.................................................34
1.3.4.2.2 Iterating through a list............................................34
1.3.4.3 Other Operations..........................................................35
1.3.4.4 Assingment instructions................................................35
1.3.5 C# Prep 5 – Functions.........................................................37
1.3.5.1 Functions vs Methods....................................................39
1.3.5.2 Variable Scope..............................................................39
1.3.5.3 Other Operations..........................................................40
Chapter 2 Abstractions.......................................................................41
2.1 Learning activity........................................................................41
2.1.1 What is Abstraction?...........................................................41
2.1.2 Objects and classes.............................................................42
2.1.2.1 Classes and files...........................................................44
2.1.3 Classes and instances.........................................................45
2.1.4 Custom data types..............................................................46
2.1.4.1 Adding behavior............................................................49
2.1.4.2 Objects within objects...................................................51
2.1.4.3 Lists of custom types....................................................52
2.1.5 Summary.............................................................................53
2.1.6 Activity instructions.............................................................54
2.1.6.1 Step 1: Design the classes............................................54
2.1.6.2 Step 2 Start the project.................................................55
2.1.6.3 Step 3: Create the job class..........................................55
2.1.6.4 Step 4: Test your Job class............................................56
2.1.6.5 Step 5: Add a display method to the job class..............56
2.1.6.6 Step 6: Create the Resume Class..................................56
2.1.6.7 Step 7: Test your resume Class.....................................57
2.1.6.8 Step 8: Add a display method to the resume class.......57
2.1.7 Reading text files in C#.......................................................58
2.1.8 Writing text files in C#........................................................59
2.1.9 Working with dates in C#....................................................59
2.2 Team activity: Designer.............................................................60
2.2.1 Journal Program...................................................................60
2.2.2 Review the program specification.......................................63
2.2.3 Determine the classes.........................................................64
2.2.4 Define class behaviors........................................................65
2.2.5 Define class attributes........................................................66
2.2.6 Review the design...............................................................67
2.2.7 Start the code.....................................................................68
2.3 Articulate activity......................................................................68
Chapter 3 Encapsulation....................................................................70
3.1 Encapsulation............................................................................70
3.1.1 Prepare................................................................................70
3.1.2 Why Encapsulation Matters.................................................71
3.1.3 Video example....................................................................72
3.1.4 Using access modifiers........................................................72
3.1.4.1 Attributes......................................................................73
3.1.4.2 Methods........................................................................73
3.1.4.3 Example........................................................................73
3.1.5 Getters and setters.............................................................74
3.1.6 On Getters and setters........................................................75
3.1.7 Constructors........................................................................76
3.1.8 Summary.............................................................................79
3.1.9 Activity instructions.............................................................79
3.1.9.1 Design the Classes........................................................79
3.1.9.2 Start the project............................................................80
3.1.9.3 Create the fraction class...............................................80
3.1.9.4 Create the constructors................................................80
3.1.9.5 Create the getters and setters......................................81
3.1.9.6 Create methods to return the representations..............81
3.1.10 Sample Solution................................................................82
3.2 Team activity: Designer.............................................................82
3.2.1 Discussing preparation learning activity.............................82
3.2.2 Review the Program Specification.......................................82
3.2.3 Determine the classes.........................................................83
3.2.4 Define class behaviors........................................................83
3.2.5 Define class attributes........................................................84
3.2.6 Define Constructors............................................................85
3.2.7 Review the Design...............................................................87
3.2.8 Conclude.............................................................................88
3.3 Scripture Memorizer..................................................................88
Chapter 4 Reinforcing abstraction and encapsulaption......................92
4.1 Learning activity........................................................................92
4.2 Activity designer........................................................................96
4.3 Participation report....................................................................96
4.4 Foundation program #1 Abstraction.........................................96
4.5 Foundation program #2 Encapsulation.....................................99
Chapter 5 Inheritance.......................................................................102
5.1 Learning..................................................................................102
5.1.1 Super and Base.................................................................104
5.1.2 Accessing private data......................................................105
5.1.3 Substitution and Is-A Relationships...................................106
5.1.4 Video demonstrations.......................................................107
5.1.5 A word of caution..............................................................107
5.1.6 In summary.......................................................................107
5.1.7 Activity instructions...........................................................108
5.2 Design activity.........................................................................111
5.3 Prove: Developer – Mindfullness..............................................118
5.3.1 Problem Overview.............................................................118
5.3.2 Solution idea.....................................................................118
5.3.3 Specification......................................................................119
5.3.4 Functional requirements....................................................119
5.3.5 Design requirements.........................................................122
5.3.6 Simplifications...................................................................123
5.3.7 Showing creativity and exceeding requirements..............123
5.3.8 Video demo.......................................................................123
5.3.9 Code helps........................................................................124
5.3.10 Design.............................................................................125
5.3.11 Develop the program......................................................126
5.3.12 Submission......................................................................126
Chapter 6 Polymorphism..................................................................127
6.1 Learning activity......................................................................127
6.1.1 A powerful combination....................................................128
6.1.2 Polymorphism in action.....................................................129
6.1.3 Abstract methods..............................................................131
6.1.4 It is all about the interface................................................132
6.1.5 Video example..................................................................133
6.1.6 In Summary.......................................................................134
6.2 Learning Activity instructions..................................................134
Chapter 1 Introduction
1.1Version control
1.1.1What is version control?
Read: About Git
By the end of this course, you will be writing programs that use a
fairly large number of files. This can seem overwhelming at first, but
as you'll learn, each one of those files will be small and narrowly
focused to one idea, so it makes working with a large system much
easier.
To prepare for this, you first need to be familiar with file and folder
organization on your computer generally, then, you'll need to learn
the conventions of how Python programs are distributed into multiple
files.
A folder can contain multiple files and also can contain other folders.
The following image shows an organization where the root, or top-
most level is a "home" folder, that contains other folders such as
"brigham" and "mary", each of which could contain other folders or
files.
Folder example
You can browse the files and folders on your computer using a
graphical file browser, and you can also navigate using a command
line terminal. You can use a terminal directly from your operating
system, or there is also a terminal window available in editors like VS
Code where you can enter commands.
The specific commands can differ between operating systems, but
they generally follow the same principles. If you are using the
command line terminal "Git Bash" on Windows, it will let you use
Linux style commands (used by MacOS as well), so those are what will
generally be shown in the course materials.
The term "directory" was more common in the command line terminal
world, but as people moved into graphical file system browsers, they
started to use the term "folder." As a programmer, you'll see both
terms and should be comfortable with them.
Tools like Git were originally designed as command line tools. There
are also Graphical User Interface (GUI) tools and plugins for most
editors that make it easy and convenient to do many things in Git.
These are great to use and can simplify your development work, but
you should also learn how to use them from the command line.
There are a few very important reasons to learn to use Git from the
command line, one is that when you tell people you "know Git", such
as on a resume or in an interview, they will assume you have a basic
understanding of how to use it at the command line as well. Another
is that while the GUI tools are very convenient when everything is in a
clean working state, sometimes unexpected things happen. When
they do, it is almost always easiest to close down the GUI tool, return
back to the command line and start with `git status` and work from
there.
2. Signed in to GitHub.
Those steps helped you create your first repository which is hosted at
GitHub.com.
Rather than having to push and pull to every person on your team, we
can instead set up a central server and have each person interface
with that. This is where GitHub comes in. GitHub allows us to host a
repository on their servers and use that as a central place for our
team. They also provide a number of other tools to aid in the
management of the repo. There are a number of other places that
provide this same functionality, but GitHub is a popular choice that
we'll use in this course.
Remember that the repository contains all the files in the project and
the complete history of changes made to them. So when you clone
this repository to your computer, you now have a copy of the
complete history showing all the changes that everyone on your team
has made.
In the Course Setup instructions, you did this when you entered the
URL for your repository and clicked "Clone this Repository." In the
background, this ran the git clone command for you.
2. Add them to a staging area where they get ready for the next
commit.
o This sends your changes and makes sure the two repos
(on your computer and at GitHub) are in sync.
1.1.7.1Adding files
To add a file to the staging area so that it can be part of the next
commit, you use the command git add followed by the name of the
file that has changed or been created. For example:
git add myFile.txt
You can also specify a directory, which will add anything that has
changed in that directory (or any subdirectories beneath it).
Remembering that the single period . represents the current
directory, you can use a shorthand syntax to add the current directory
and everything beneath it by typing:
git add .
If you would like to use the VS Code extension for Git, you can click on
the Source Control tab on the left menu. This will show you any files
that have changed. You can click the "+" icon next to any of these
files to add them to the staging area for the next commit.
In fact, it is so important to leave a message that Git will not let you
do a commit without a message.
If you are using the VS Code extension for Git, on the Source Control
tab on the left menu, there is a box for you to type your message and
then you can click the button to commit.
If you forget to include a commit message, git will take you to a text
editor to type one in. On most systems this will take you to a flavor an
editor called vi by default. This may or may not be your favorite
editor. If it is not, and you simply want to exit, press the Escape key a
couple of times and then type :q! (the : tells it you are entering a
command, the q says you want to quit, and the ! says you are not
worried about saving changes).
This will help you exit the editor. You can then run the commit
command again, this time with the -m for your message.
In this example, "origin" is the name of the remote server, and the
word "origin" is convention for your main server. The word "main" is
the branch that you would like to push to in case you are trying to
keep certain changes separate from one another. This semester we
will always use "origin" and "main". And, in fact, when you clone a
repo from GitHub, these will be set as defaults, so if you want to use
them, you only need to type:
git push
If you are using the VS Code Extension for Git, on the Source Control
tab on the left side, after you have committed your changes, you can
click the button to "Sync Changes", or alternatively, you can click on
the three dots and select "Push".
When you sync, it will check for any changes that have been made at
GitHub and pull them down, and then push your changes up. Because
you are the only one working on your project, you will likely not need
to pull any changes down.
The Git command to see the changes made in any file is “git status”.
To update the changes to the main project the command is “git add
“file location””
Ensure that your tools are installed and that you can compile and run
a basic program in C#.
Preparation Material
In addition to the text here, you should consider the Web as a primary
source for learning. Once you know what to do, but just not how to do
it in a certain language, it's easy to search for "C# print statement" or
"C# for loop" or even something more complicated like, "C# open file
and read line by line". StackOverflow, in particular, is a great site to
help you with these kinds of questions.
Defined types
You declare a variable, by specifying the type. Later, when you use
the variable, you do not need to specify the type again.
int x;
x = 5;
Console.WriteLine(x);
Python
print("Hello World!")
C#
Console.WriteLine("Hello World!");
Also, please be aware that, unlike input in Python, you do not provide
the text of the prompt to the Console.ReadLine() function in C#, so
you must display it first with Console.Write("").
Python
C#
Also, in C#, you do not use a colon : to start the body, and when
using if statements, you must always put the condition in
parentheses ().
C#
if (x > y)
{
Console.WriteLine("greater");
}
Python
if x > y:
print("greater")
As you may have noticed above, in C#, statements end with the
semicolon ; character. Typically one statement will be one line,
however, sometimes you may have a long statement that extends on
multiple lines until the semicolon ; is reached.
String Interpolation
In C#, if you would like to use a variable inside a string, you start the
string with a dollar sign $ in the same way that in Python, you start a
format string with an f.
Python
school = "BYU-Idaho"
print(f"I am studying at {school}.")
C#
string school = "BYU-Idaho";
Console.WriteLine($"I am studying at {school}.");
Video Demo
Assignment Instructions
Learning activities
As you will see, each learning activity in this course will have two
components, they begin with preparation material to read or watch,
and then there is a small programming assignment where you
practice the concepts you have just read.
You need to finish this assignment and then return to Canvas to report
on your work.
Now that you have seen basic C# syntax, complete the following
assignment. This was a program you completed earlier in CSE 110,
but in this case, you will write the program in C#.
4. On the "Run and Debug" menu, select "C# Prep 1" from the
dropdown menu and click the green play button to run the
program. In the terminal window, it should display the
text Hello Prep 1 World!.
Program Specification
Here are the instructions that you saw previously in CSE 110 that we
will use as our program specification:
Overview
An iconic line from the James Bond movies is that he would introduce
himself as "Bond, James Bond." For this assignment you will write a
program that asks for your name and repeats it back in this way.
Assignment
Prompt the user for their first name. Then, prompt them for their last
name. Display the text back all on one line saying, "Your name is last-
name, first-name, last-name" as shown:
Make sure to be precise! You should have the spacing, comma, and
period appear exactly as shown in the examples.
If you have an error in your program and try to run it, VS Code will tell
you that it cannot build a new version of your program to run. But, it
may find an old version from the last time it successfully built the
program. If you click "Debug Anyway" it will run the old version.
Sample solution
When you have finished the program, please compare your approach
to the one from this sample solution:
If you are having difficulty with this and future programs, you are
welcome to look at the sample solution to help you finish it.
Remember, though that the goal is for you to learn how to write code
on your own, and often we learn this best by working through a
number of things that don't work, before we find the one that does
work. So don't jump in here too quickly.
Also, you should make sure that you type every line of code yourself.
Do not copy and paste this code. It is important for your learning that
you practice writing every line of code.
1.3.2.1Conditionals
1.3.2.1.1If statements
First, the condition of the if statement must be put in parentheses ().
Then, to define the body of the if statement, you still indent by
convention, but it is the curly braces {} that define the body. (You
also do not use the colon : that Python does to start the block.)
C#
if (x > y)
{
Console.WriteLine("greater than");
}
Python
if x > y:
print("greater than")
Notice that the convention in C# is to put the curly braces {} on their
own lines. There are religious debates about "the one true bracing
style," but putting them on their own line is the defined convention
for C#, so that's what you should follow.
if (x > y)
{
if (x > z)
{
Console.WriteLine("greater than both");
}
}
C#
if (x > y)
{
Console.WriteLine("greater than");
}
else
{
Console.WriteLine("less than");
}
Python
if x > y:
print("greater than")
else:
print("less than")
The else if condition also defines its body in the same fashion. Please
note that in C#, the keywords are else if not elif:
C#
if (x > y)
{
Console.WriteLine("greater than y");
}
else if (x > z)
{
Console.WriteLine("greater than z");
}
else
{
Console.WriteLine("less than both");
}
Python
if x > y:
print("greater than y")
elif x > z:
print("greater than z")
else:
print("less than both")
1.3.2.1.3 Operators
C# uses the == operator to check if two variables are equal, just like
in Python. It also supports other operators you are familiar with, such
as !=, >=, <=, and so forth:
if (name == "John")
{
Console.WriteLine("The name is John");
}
if (color != favoriteColor)
{
Console.WriteLine("That color is not my favorite");
}
1.3.2.1.4
And, Or, and Not Operators
In C#, the and operator is && the or operator is || and
the not operator is ! which can be combined together with other
expressions and parentheses.
This is especially important if the value comes from the user via
a Console.ReadLine() statement, which always returns a string:
Console.Write("What is your favorite number? ");
string userInput = Console.ReadLine();
int number = int.Parse(userInput);
If the user typed in something other than a number, this would result
in type of error called a Runtime Exception.
Video Demo
https://byui-cse.github.io/cse210-ww-course/week01/csharp-2.html
1.3.2.4 Assignment Instructions
For this assignment, you will complete another assignment that you
did previously in CSE 110, but in this case, write the program in
C#:
Program Specification
Here are the instructions that you saw previously in CSE 110 that we
will use as our program specification:
Overview
A >= 90
B >= 80
C >= 70
D >= 60
F < 60
Assignment
Core Requirements
1. Ask the user for their grade percentage, then write a series
of if-elif-else statements to print out the appropriate letter
grade. (At this point, you'll have a separate print statement for
each grade letter in the appropriate block.)
2. Assume that you must have at least a 70 to pass the class. After
determining the letter grade and printing it out. Add a separate
if statement to determine if the user passed the course, and if
so display a message to congratulate them. If not, display a
different message to encourage them for next time.
3. Change your code from the first part, so that instead of printing
the letter grade in the body of each if, elif, or else block,
instead create a new variable called letter and then in each
block, set this variable to the appropriate value. Finally, after
the whole series of if-elif-else statements, have a single print
statement that prints the letter grade once.
Stretch Challenge
1. Add to your code the ability to include a "+" or "-" next to the
letter grade, such as B+ or A-. For each grade, you'll know it is a
"+" if the last digit is >= 7. You'll know it is a minus if the last
digit is < 3 and otherwise it has no sign.
After your logic to determine the grade letter, add another section to
determine the sign. Save this sign into a variable. Then, display both
the grade letter and the sign in one print statement.
Hint: To get the last digit, you could divide the number by 10, and get
the remainder. You might review the standard math operators and
find the one that does division and gives you the remainder.
At this point, don't worry about the exceptional cases of A+, F+, or F-.
4. Make sure to use the same project template that you did for the
C# Prep 1 activity. However, this time, you should add your
code in Program.cs file in the the Prep 2 project.
Sample Solution
When you have finished the program, please compare your approach
to the one from this sample solution:
do-while
for
foreach
1.3.3.1.1While loops
While loops in C# work exactly the same way as in Python or other
languages. The only difference is that C# uses curly braces {} to
define the body of the loop, and the condition, must be surrounded by
parentheses ().
C#
Python
response = "yes"
The syntax for a do-while loop is to use the keyword do, followed by
the body, followed by the the while keyword with the expression and
a semi-colon as shown:
string response;
do
{
Console.Write("Do you want to continue? ");
response = Console.ReadLine();
} while (response == "yes");
1.3.3.1.3 For loops
The standard for loop in C# is more like a "for x in range" loop in
Python. The condition has three parts, separated by semi-colons. The
first initializes the value, the second is the condition to check, and the
third is an increment step that is run at the end of each loop.
The following code shows the syntax of a for loop that counts from 0
to 9.
In that code, you will see the use of the ++ operator which
increments the value in the variable by one.
The code above is the most common way to see one of these loops,
but you could put other values or statements in these spots, such as
counting from 2 to 20 by two's:
Program Specification
Here are the instructions that you saw previously in CSE 110 that we
will use as our program specification:
Overview
Core Requirements
1. Start by asking the user for the magic number. (In future steps,
we will change this to have the computer generate a random
number, but to get started, we'll just let the user decide what it
is.)
At this point, the user should be able to keep playing until they get
the correct answer.
Stretch Challenge
1. Keep track of how many guesses the user has made and inform
them of it at the end of the game.
2. After the game is over, ask the user if they want to play again.
Then, loop back and play the whole game again and continue
this loop as long as they keep saying "yes".
4. Make sure to use the same project template that you did for the
previous activities. However, this time, you should add your
code in Program.cs file in the the Prep 3 project.
Sample Solution
When you have finished the program, please compare your approach
to the one from this sample solution:
1.3.4.1.1 Lists
As you know, a major difference between C# and Python is that you
must declare your variable types in C#. While at first, this may seem
like a burden in C#, you'll soon discover that it helps you avoid many
runtime errors.
In a similar way, when you declare a new list variable in C#, you not
only declare that it is a List, you must also declare the type of data
that can be put in the list. That way, if you create a list of users, you
will be prevented from accidentally adding an order or a product
variable to this list.
Rather than having to implement separate code for the data structure
for every kind of data that could ever be put into it, the developers of
the C# List library make use of a concept called "Generics."
With generics, the library is written generically and then the type can
be provided to fill in the template. In documentation, you'll often
see T used as the template value to be filled in later.
List<int> numbers;
List<string> words;
The code above declares a variable to hold the list, but before you
can use one, you need to create a new one to use with
the new keyword.
List<int> numbers;
numbers = new List<int>();
Notice the extra parentheses () at the end, that we use any time we
create a new object.
One more important thing to be aware of: Any file that uses Lists
(or any other standard collection), must refer to that library at the top
of the file. (This is so common that sometimes your settings for C#
can be specified so that you do not not have include this, but it is
important to know about it, in case you run into problems.)
using System.Collections.Generic;
It turns out that List is a class or custom data type and we are
creating a new object or instance of that class. This is actually the
complete focus of this course, and beginning next week you will learn
how to create your very own custom classes.
With this in mind, you will learn much more about this in coming
weeks, but for now, just remember to include new before you start
using a list.
C#
using System.Collections.Generic;
...
words.Add("phone");
words.Add("keyboard");
words.Add("mouse");
Python
words = []
words.append("phone")
words.append("keyboard")
words.append("mouse")
C#
Console.WriteLine(words.Count);
Python
print(len(words))
C#
Python
C#
Python
for i in range(len(words)):
print(words[i])
1.3.4.3Other Operations
There are many other things you can do with lists. You can view the
official documentation or also, just begin typing in VS Code and see
the options that the Intellisense editor pops up for you.
In addition, don't forget that you can easily find syntax with a quick
Web search!
Program Specification
Here are the instructions that you saw previously in CSE 110 that we
will use as our program specification:
Assignment
Ask the user for a series of numbers, and append each one to a list.
Stop when they enter 0. (Remember: You should not add 0 to the
list. If you do, later calculations and operations will not be correct.)
Core Requirements
Stretch Challenge
1. Have the user enter both positive and negative numbers, then
find the smallest positive number (the positive number that is
closest to zero).
2. Sort the numbers in the list and display the new, sorted list.
Hint: There are C# libraries that can help you here, try
searching the internet for them.
The following shows the expected output after completing the stretch
challenges:
Enter a list of numbers, type 0 when finished.
Enter number: 3
Enter number: 5
Enter number: 7
Enter number: 3
Enter number: 2
Enter number: -1
Enter number: -4
Enter number: -8
Enter number: 0
The sum is: 7
The average is: 0.875
The largest number is: 7
The smallest positive number is: 2
The sorted list is:
-8
-4
-1
2
3
3
5
7
Sample Solution
When you have finished the program, please compare your approach
to the one from this sample solution:
One key difference in C# is that in the same way that each variable
must define a type, each function must define its return type, for
example, whether it will return an int, a string, or nothing (the return
type for nothing is void). Also, each parameter must have a data type
as well. This is very helpful because, unlike in Python, you will know
exactly what kind of data you are receiving.
The style guidelines for C# say that a function name should use "Title
Case" where the name begins with a capital letter and then each
subsequent word is capitalized such as: ThisIsALongFunction.
C#
void DisplayMessage()
{
Console.WriteLine("Hello world!");
}
Python
def display_message():
print("Hello World")
The next example shows a function that accepts a single string
parameter:
C#
Python
def display_personal_message(user_name):
print(f"Hello {user_name}")
C#
Python
1.3.5.1Functions vs Methods
From previous courses, you may recall a distinction between
standalone functions and member functions, which are
called methods. Methods play a very important role in Programming
with Classes and they will be discussed at length in the coming
lessons.
Until we start writing classes, you should put the static keyword in
front of all your functions.
Use static for all of your functions until we start writing classes.
Also, don't forget that you can easily find syntax with a quick Web
search!
Assignment Instructions
For this assignment, write a C# program that has several simple
functions:
Your Main function should then call each of these functions saving the
return values and passing data to them as necessary.
2. Make sure to use the same project template that you did for the
previous activities. However, this time, you should add your
code in Program.cs file in the the Prep 5 project.
Sample Solution
When you have finished the program, please compare your approach
to the one from this sample solution:
Objects have state and behavior that allow them fulfill their
responsibility. The person object may have state like "given name"
and "family name". It may also have related behaviors like "show
western name" and "show eastern name". Following is a graphical
depiction of our person object.
Person responsabilities
There aren't any unrelated behaviors either. There are certainly many
other ones we could think of as belonging to a person. However, our
conceptualization only contains those that help fulfill its specific
responsibility.
You can observe from the class diagram that the standard in C# is
to use TitleCase for class and method names, and to use
_underscoreCamelCase for our member variable names. The
underscore at the beginning helps you recognize that the variables
are members of the class and are different from regular, local
variables.
There are many tools to help you create class diagrams, and as you
learn about more details of programming with classes you will learn
that there are lots of elements that can be added to a diagram.
Behaviors:
* ShowEasternName() : void
* ShowWesternName() : void
2.1.3 Classes and instances
By itself, a class is just a template for something. It only
becomes useful when an instance is created and assigned to a
variable in your program. An instance is the realization of
attributes and methods in the computer's memory.
Output
Joseph Smith
Smith, Joseph
Output
Emma Smith
Joseph Smith
This code creates boxes that you can later fill with values. Then, when
you assign the value, it puts it in the box. For example, the following
code puts the number 17 in the box:
height = 17;
With this new custom data type, you can now create a new variable
whose type is Blind. We can think about this as creating a new box
for it. The difference is that this box has a little separator inside it
making three smaller compartments, one for each of the three
member variables.
Every time you create a new Blind variable, it creates another large
box that has these three components. The class is what defines the
structure of the large box, and each of these large boxes that you
create is an object or instance of that class.
For example:
Blind kitchen = new Blind();
The GetArea() function now belongs inside the box as well. And
because it is inside the box, you use the "dot" notation to call it:
double materialAmount = kitchen.GetArea();
(The red lines in the image are meant to indicate that there are lines
of code associated with this method.)
kitchen._width = 60;
kitchen._height = 48;
kitchen._color = "White";
The fact that the method accesses the member variables in its box, is
also why GetArea() will return different values for
different Blind objects, such
as kitchen.GetArea() and livingRoom.GetArea(), because these
two objects will have different values for their widths and heights.
2.1.4.2 Objects within objects
Remember, that you must initialize these blinds to new values. You
can do this after you create a new House object:
House johnsonHome = new House();
Or, you can initialize these variables right in the class definition:
public class House
{
public string _owner = "";
public Blind _kitchen = new Blind();
public Blind _livingRoom = new Blind();
}
Once you have created a new House object, you can access its
member variables using the "dot" operator just as before:
House johnsonHome = new House();
johnsonHome._owner = "Johnson Family";
When you want to access the internal values of one of these complex-
type, member variables, you can just chain together multiple "dot"
operations, such as:
johnsonHome._kitchen._width = 60;
In the same way that you can create a list of strings or a list of
doubles, you can also create a list of a new custom type. For example,
instead of the House class containing variables for the kitchen and
the living room blinds, it might have a list of blinds:
public class House
{
public string _owner;
public List<Blind> _blinds = new List<Blind>();
}
With this new version of the House class, you could write code like:
johnsonHome._blinds.Add(kitchen);
or:
double amount = johnsonHome._blinds[0].GetArea();
or:
foreach (Blind b in johnsonHome._blinds)
{
double amount = b.GetArea();
}
The following figure shows the way you might think about the storage
of the johnsonHome object. Notice that the _blinds member
variable now refers to a list of Blind objects. Each Blind object can be
referenced by its index, and each has its own values for
the _width, _height, and _color variables.
2.1.5 Summary
Instance - A variable whose data type is the class. We often use the
term Object interchangeably. Example: We can have two instances of
the Person class: one for John, and one for Mary.
Class: Job
Responsibilities:
o Keeps track of the company, job title, start year, and end
year.
Behaviors:
Class: Resume
Responsibilities:
Behaviors:
Based on these descriptions, you could create class diagrams like the
following:
3. Verify that you can run the project and see the beginning "Hello
World" output.
1. Create a new file for your job class. By convention this should
be named Job.cs .
2. Create the class (Hint this is the public class Job syntax).
3. Create member variables in the class for each element that this
class should contain. By convention these member variables
should begin with an underscore and a lowercase letter such
as _jobTitle .
4. Verify that you can display the company of this job on the
screen, again using the dot notation to access the member
variable.
Sample Output
Microsoft
Apple
2. This method should display the job details on the screen in the
correct format. Remember that the method can access the
member variables directly, without needing them to be passed
into it.
Sample Output
Software Engineer (Microsoft) 2019-2022
Manager (Apple) 2022-2023
1. Create a new file for your Resume class. Each class should be
in its own file and the file name should match the name of the
class.
4. Create the member variable for the list of Jobs. (Hint: the data
type for this should be List<Job> , and it is probably easiest to
initialize this to a new list right when you declare it..)
2. Add the two jobs you created earlier, to the list of jobs in the
resume object.
3. Verify that you can access and display the first job title using
dot notation similar to myResume._jobs[0]._jobTitle .
2. This method should not have any parameters and should not
return anything.
3. In the method body, you should display the person's name and
then iterate through each Job instance in the list of jobs and
display them.
4. Hint: remember that you can call each job's Display method
that you created earlier.
5. Return to your main function, remove any code that is
displaying information, and instead, add a call at the end to
the Display method from your Resume class to display the
name and all the jobs in one line.
Sample Output
Sample Solution
Submission
The easiest way to read a text file in C# is to read the entire file into
an array of strings (one per line) using
the System.IO.File.ReadAllLines() function. Then, you can iterate
through each string as you would with any list.
There are many other ways to work with files in C# some of which
would be more efficient if the file is very large and you don't want to
store it all in memory at once, but this approach will work just fine for
this project.
To make sure the file gets closed and cleaned up appropriately when
you are done, it is best practice to put the StreamWriter object in
a using() block. This works the same as a "with" block in Python and
ensures that the resources are cleaned up when you leave that area
of the code.
...
You can get an object representing the current day and time
with DateTime.Now. Then, it has various methods that are helpful,
such as .ToShortDateString().
DateTime theCurrentTime = DateTime.Now;
string dateText = theCurrentTime.ToShortDateString();
Think to yourself for a moment: What are some reasons people do not
follow through with their goal to keep a journal? Could a program or
app help with any of these?
We forget
It's not convenient to get out our written journal or find the
electronic document
Solution Idea
These features could help address some of the challenges that keep
people from journaling, and could be included in a mobile app or on a
web page. The actual interface is not that critical, but the ability for a
program to help solve a real problem is important to recognize.
Program Specification
For this assignment you will write a program to help people record the
events of their day by supplying prompts and then saving their
responses along with the question and the date to a file.
Functional Requirements
1. Write a new entry - Show the user a random prompt (from a list
that you create), and save their response, the prompt, and the
date as an Entry.
2. Display the journal - Iterate through all entries in the journal and
display them to the screen.
3. Save the journal to a file - Prompt the user for a filename and
then save the current journal (the complete list of entries) to
that file location.
4. Load the journal from a file - Prompt the user for a filename and
then load the journal (a complete list of entries) from that file.
This should replace any entries currently stored the journal.
Design Requirements
Simplifications
For the core requirements you do not need to worry about the
following:
Video Demo
The following video demonstrates the way this program should work:
The following video demonstrates the way this program should work:
Submission
A record for the writings in the text files, options for the user to
choose.
Write
Display
Load
Save
My proposal
Class Responsibility
Write To show questions to the user
and store the answers in empty
variables.
Display It shows the user entries
Load To read from a file the answers
and display them
Save It saves the user entries in a file
Class: Person
Attributes:
* _givenName : string
* _familyName : string
Behaviors:
* ShowEasternName() : void
* ShowWesternName() : void
Mentor proposal
Class Responsibility
Journal Stores a list of journal entries
Entry Represents a single journal entry
PromptGenerator Supplies random prompts
whenever needed
In addition, your program will also have a Program class that is the
starting point for the program and handles much of the user
interaction. Because all programs contain this class, and because it
is usually simple, only containing a few static methods, and we do
not not even create an instance of it, you will often see it excluded
from lists like this, where instead, we focus on the classes that
model the components of our specific problem.
You might have also considered a "file" class, but in this case, the
main concepts to model are the journal and the entry. Being able to
load and save these journal entries could be behaviors of these
classes, and then you wouldn't need an extra File class. It could
certainly be a valid approach to have a class for all the file
interaction with methods like SaveToFile and LoadFromFile. These
are the hard decisions that programmers have to weigh back and
forth. For this program, we will let the Journal class take care of this
behavior.
Does the prompt generator really need to be it's own class or could
it simply be a method? This is a good question. But by making the
prompt generator a class, it can abstract any details associated with
generating prompts, such as whether they are loaded from a file,
scraped from an internet source, or to make sure make sure
duplicate prompts are not given. You may not want all those
features now, but the benefit of abstraction is that you could add
them later on and not have to change the way the rest of the
program works. So, for that reason, it makes good sense to create it
as a class now.
2.2.4 Define class behaviors
Now that you have decided on the classes you will need and their
responsibilities, the next step is to define the behaviors of these
classes. These will become the methods of each class.
1. What are the behaviors this class will have in order to fulfill its
responsibilities? (In other words, what things should this
class do?)
Many behaviors of the Journal class also come out nicely from the
specification. For example, a journal needs to include behaviors such
as:
Adding an entry
Saving to a file
The Entry class doesn't have too many behaviors. It's main
responsibility is to hold data. And yet, because it is in charge of
everything that has to do with entries, it would make sense for it to at
least have it's own display method. Then, the Journal display method
could iterate through all Entry objects and call the Entry display
method. The Journal wouldn't have to worry about the details of how
the Entry was displayed, this would all be contained within
the Entry class.
Journal
o AddEntry(newEntry : Entry) : void
o DisplayAll() : void
o SaveToFile(file : string)
o LoadFromFile(file : string)
Entry
o Display() : void
PromptGenerator
o GetRandomPrompt() : string
What are the potential benefits of having a Display method in
the Entry class rather than allowing the Journal's display method to
display an entry's date and text directly?
If the Entry variables are renamed, other classes would not have to be
updated.
Now that you have defined the classes, their responsibilities, and their
behaviors, the next step is to determine what attributes the class
should have, or what variables it needs to store.
1. What attributes does this class need to fulfill its behaviors? (In
other words, what member variables should this class store?)
A Journal should store a list of Entry objects. The data type for this
should be List<Entry>
An Entry should keep track of the date, prompt text, and the text of
the entry itself.
Converting these ideas into concise variable names along with their
data types gives us the following:
Journal
o _entries : List<Entry>
Entry
o _date : string
o _promptText : string
o _entryText : string
PromptGenerator
o _prompts : List<string>
The following is a final class diagram for each of the classes that you
can use as a guide as you being writing your code.
Using this design, when you want to add a new entry to the journal,
you will use code such as theJournal.AddEntry(anEntry); instead
of using the _entries variable and its add method like
this theJournal._entries.Add(anEntry);. What is a benefit of our
design approach (the AddEntry method), instead of accessing the
variable directly?
Now that you have a design for your classes in mind. The next step is
to start the code of the program.
If the function has a void return type, meaning it does not return
anything, it can be left completely empty.
1. Open the project in VS Code. Create new files that contain the
"stubs" or empty code for all the classes, member variables,
and functions in your design.
o Each class should be in its own file and the name of the
file should match the class name (for
example, Journal.cs).
One benefit of classes is that they are pieces of code that are
reusable, e.g. they can be used in a program the same as other
methods are used.
To use this class in any other program the following must be done
Code
Output
Laura
Damian
Luz
Joel
By simply assigning a list to the attribute and calling the method the
behavior is applied.
Chapter 3 Encapsulation
3.1Encapsulation
Overview
3.1.1Prepare
Encapsulation is the act of enclosing something, as if it were in
a capsule. It means thinking carefully about the behaviors your
classes need and then hiding the details of how they perform those
behaviors, even making it so other code cannot see or manipulate
these details.
In this case, the details of the Account class are not well
encapsulated. We need a way of hiding the class attributes so that
other code does not attempt to change them directly. If we can, it will
allow us to minimize the interdependencies between different parts of
our code and protect them from breaking changes.
In C#, Any class members that should be kept private or hidden from
other parts of the program should begin with the private keyword.
Any class members that should be available for use in other parts of
the program should begin with the public keyword. These are called
access modifiers.
The idea is to limit access to only those parts of the code they really
need it.
3.1.4.1 Attributes
As a general rule, attributes (or member variables) should be
made private. Other classes should not know the details of how the
class stores its information. Instead, the other parts of the program
should ask the class to perform tasks related to that information
through public methods.
...
}
3.1.4.2Methods
Many methods (or member functions) of a class are public. This is the
interface that other parts of the program can use to perform the tasks
they need.
Are there ever private methods? Yes! Often, a public method will have
internal steps or computations to perform to help it do its job. These
"helper functions" are often private, because the only code that needs
to access them is in the class.
In order to get the full name from a class that stores the first and last
names separately, the class might make use of a private, helper
function to prepare the full name. This function could be made private
initially, because others only need access to the email signature. (If it
is later determined that others need access to the full name itself, you
could consider making it public as well. But in all cases you are
keeping the variables private.)
...
}
This would then be called from another part of the program as follows:
Console.WriteLine(p.GetFirstName());
Notice that the other part of the program now has the ability to set
the first name, and can also access it when needed, but it does so
by calling these methods, rather than interacting with the
variables directly.
C# Properties
For all these reasons, as you get started with getters and setters, you are
encouraged to use the actual getter and setter methods. Then, as you get
more comfortable with them, it will be an easy switch for you to begin using
3.1.7 Constructors
In the previous lesson you were introduced to Constructors.
Constructors are special methods that are called
automatically when an object is created. Their purpose is to help
set up the initial state of an object. The name of a constructor must
match the class name, and the return type is left empty (not
even void). The simplest constructor is a no-argument constructor,
that allows an object to be created without specifying any extra
information.
You can use this constructor to help set default values. For example,
the following code specifies a no-argument constructor to set a
default name for all new Person objects that are created.
public Person()
{
_title = "";
_firstName = "Anonymous";
_lastName = "Unknown";
}
...
public Person()
{
_title = "";
_firstName = "Anonymous";
_lastName = "Unknown";
}
You can indicate constructors in your class diagram just like methods,
but without a return type. For example:
Person class
Diagram
3.1.8 Summary
Encapsulation is the second principle of programming with classes. A
key component of encapsulation is hiding or controlling access to
information. Careful use of access modifiers will help protect you and
your coworkers from breaking your programs.
3. The class should have two attributes for the top and bottom
numbers.
4. Make sure the attributes are private.
o Constructor that has one parameter for the top and that
initializes the denominator to 1. So that if you pass in the
number 5, the fraction would be initialized to 5/1.
o Constructor that has two parameters, one for the top and
one for the bottom.
2. In your Program.cs file, verify that you can call all of these
methods and get the correct values, using setters to change the
values and then getters to retrieve these new values and then
display them to the console.
3. Verify that you can call each constructor and that you can
retrieve and display the different representations for a few
different fractions. For example, you could try:
o 1
o 5
o 3/4
o 1/3
Sample Output
1/1
1
5/1
5
3/4
0.75
1/3
0.3333333333333333
Remember:
Getters should not have any parameters and should not prompt
the user for anything, but instead, simply return a value.
The program can end in one of two ways: Either the user types
quit, or all of the words in the scripture have been hidden.
The following are good choices for classes, listed with their
responsibilities:
Scripture: Keeps track of both the reference and the text of the
scripture. Can hide words and get the rendered display of the
text.
1. What are the behaviors this class will have in order to fulfill its
responsibilities? (In other words, what things should this
class do?)
The key behaviors for the Word class are to hide and show a word
and to check if a word is hidden or not. In addition, a Word should
have a behavior to get the display text of that word, which would be
either the word itself (for example, "prayer") or, if the word were
hidden, this behavior would return underscores (for example,
"______").
Scripture
o HideRandomWords(numberToHide : int) : void
o GetDisplayText() : string
o IsCompletelyHidden() : bool
Word
o Hide() : void
o Show() : void
o IsHidden() : bool
o GetDisplayText() : string
Reference
o GetDisplayText() : string
o Possible getters and setters
Ramdom method
What is a benefit of the Reference class containing its
own GetDisplayText method, instead of having the Scripture
class display the book chapter and verse directly?
1. What attributes does this class need to fulfill its behaviors? (In
other words, what variables should this class store?)
The Scripture class will need member variables for a reference and
list of all of the words in the scripture. The data type for the reference
is Reference, the custom class defined above. The data type for the
list of words would be List<Word> (notice it is a list of Word objects,
rather than a list of strings.)
The Word class will need to store the text of the word itself (a string)
and a variable to indicate whether that word is shown or hidden (a
boolean).
The Reference class will need to store a variable for the book
(string), the chapter (int), and the verse (int). Then, it will also need to
store one additional variable for second, or "end," verse of the range
to handle the case of Proverbs 3:5-6.
Scripture
o _reference : Reference
o _words : List<Word>
Word
o _text : string
o _isHidden : bool
Reference
o _book : string
o _chapter : int
o _verse : int
o _endVerse : int
Remember that constructors help set up the initial state of the object,
so you should consider what data is necessary for that initial state.
While including the logic of creating the word list may seem like a lot
of work for the constructor, it is helpful to encapsulate this logic in
the Scripture class so that other code does not have to worry about
the internal storage of the Scripture. This would enable the program
to be easily changed in the future, if a different implementation
choice were made.
The following is a final class diagram for each of the classes that you
can use as a guide as you being writing your code.
3.2.8 Conclude
At this point, you have the design of the classes you will need for this
project. If your design is not "perfect," or it needs to change as you
begin working on the project, that is just fine! As you learn more
details, you will naturally need to adjust your planning. This is why the
principles of programming with class are so valuable, because they
allow your program to easily change.
1. Determine who will be the lead student for the next meeting.
After the team activity, each person needs to individually do the the
following:
1. Open the project in VS Code. Create new files that contain the
"stubs" or empty code for all the classes, member variables,
and functions in your design.
o Each class should be in its own file and the name of the
file should match the class name.
2. Make sure that your program can build without errors.
3. Submission
Specification
Functional requirements
6. If the user presses the enter key (without typing quit), the
program should hide a few random words in the scripture, clear
the console screen, and display the scripture again. (Hiding a
word means that the word should be replace by underscores (_)
and the number of underscores should match the number of
letters in that word.)
7. The program should continue prompting the user and hiding
more words until all words in the scripture are hidden.
8. When all words in the scripture are hidden, the program should
end. (The final display of the scripture should show the scripture
with all words hidden.)
Design Requirements
The following video demonstrates the way this program should work:
Code Helps
You might find the following code helps useful in this project:
In the demo video, you can see that when the user pressed the enter
key, words on the screen "disappeared" or were replaced by
underscores. In reality, what happened is the console was cleared,
and then the scripture was printed out again, but this time with
underscores in place of certain words.
Design
You will work with your team to create a design for this program.
Then, you will each write the code for the program individually.
For reference purposes, here is a copy of the design that was created
during the design activity.
In order to understand the decisions that led to this design, make sure
to walk through the design activity step by step before using this
design to start your code.
Develop the Program
Submission
Question 1
1 / 1 pts
What is the primary goal of abstraction in programming?
Question 2
1 / 1 pts
In object-oriented programming, abstraction is typically achieved
using:
Loops
Classes
Conditionals
Lists
Question 3
1 / 1 pts
What is the relationship between a class and an instance?
Classes are like templates. Instances are the actual objects created in
memory, using that template.
Question 4
1 / 1 pts
Objects can contain other objects as member variables.
True
False
Question 5
1 / 1 pts
What is a method?
A custom class.
Question 7
1 / 1 pts
When we talk about information hiding in a program, who are we
hiding it from?
Potential hackers.
Question 8
1 / 1 pts
Methods can call other methods.
True
False
Question 9
1 / 1 pts
Why might blindly creating getters and setters be a bad idea?
Because they are exposing the way the data is stored internally,
reducing the benefits of information hiding.
Because they require so many unit tests to be created that they are
not helpful.
Question 10
1 / 1 pts
In C#, if you do not define any constructors what happens?
You will only be able to create one object from the class.
Conclude
At this point, you have the beginning of a design for the classes you
will need for your programs. It is ok if your designs are not perfect or
need to change once you think about it more deeply.
Overview
Scenario
Note: The YouTube example is just to give you a context for creating
classes to store information. You will not actually be connecting to
YouTube or downloading content in any way.
Program Specification
Your program should have a class for a Video that has the
responsibility to track the title, author, and length (in seconds) of the
video. Each video also has responsibility to store a list of comments,
and should have a method to return the number of comments. A
comment should be defined by the Comment class which has the
responsibility for tracking both the name of the person who made the
comment and the text of the comment.
Once you have the classes in place, write a program that creates 3-4
videos, sets the appropriate values, and for each one add a list of 3-4
comments (with the commenter's name and text). Put each of these
videos in a list.
Then, have your program iterate through the list of videos and for
each one, display the title, author, length, number of comments (from
the method) and then list out all of the comments for that video.
Repeat this display for each video in the list.
User Interaction
The focus of the Foundation programs is to help you design and build
the classes and work with the relationships among these classes. With
that in mind, you do not need to create a menu system or a user
interface. Instead, your Program.cs file should create the required
objects, set their values, and display them as specified, without any
user interaction.
Showing Creativity
Submission Instructions
Because this project does not have any user interaction, for
submission, you will include a screenshot of your program execution
in your GitHub repository alongside the corresponding code. (See
below for detailed instructions about capturing a screenshot.)
Capturing a Screenshot
3. Capture screenshot.
o On Windows:
o On Mac:
Capture screenshot with Command + Shift + 3
(screenshot will be automatically saved to your
Desktop).
6. View your project on GitHub and verify the screenshot has been
added.
Overview
Scenario
Assume you have been hired to help a company with their product
ordering system. They sell many products online to a variety of
customers and need to produce packing labels, shipping labels, and
compute final prices for billing.
Program Specification
Order
The total price is calculated as the sum of the total cost of each
product plus a one-time shipping cost.
Product
Customer
Address
The address contains a string for the street address, the city,
state/province, and country.
Other considerations
Make sure that all member variables are private and getters, setters,
and constructors are created as needed.
Once you have created these classes, write a program that creates at
least two orders with a 2-3 products each. Call the methods to get the
packing label, the shipping label, and the total price of the order, and
display the results of these methods.
User Interaction
The focus of the Foundation programs is to help you design and build
the classes and work with the relationships among these classes. With
that in mind, you do not need to create a menu system or a user
interface. Instead, your Program.cs file should create the required
objects, set their values, and display them as specified, without any
user interaction.
Showing Creativity
Submission Instructions
Because this project does not have any user interaction, for
submission, you will include a screenshot of your program execution
in your GitHub repository alongside the corresponding code. (For
detailed instructions about capturing a screenshot, see
the Foundation #1 program description.)
5.1 Learning
What is Inheritance?
Inheritance is the ability for one class to obtain the attributes and
methods of another class directly, without having to type them. It
follows the same idea of people inheriting certain characteristics from
their parents.
Output
Joseph
A class diagram showing this relationship shows the base class on top
and the derived class beneath it. An arrow with an open arrowhead
goes from the derived class to the base class.
Output
Brigham
234
In this example, the Student class inherits from the Person class.
The Student constructor calls the Person constructor using
the base keyword, and passes the name parameter through.
...
There are two ways to fix this problem. The first is to create a getter
for the _name variable in the base class and then, in this method,
you could call the getter to access the value.
So which is better?
Rule of thumbs:
Patrick Wyatt, a long time game developer, wrote about this problem
in a blog post called, Tough times on the road to Starcraft. Inheritance
belongs in programs with classes. However, Mr. Wyatt's experience is
very instructive.
5.1.6 In summary
Inheritance is the third principle of programming with classes. The key
to understanding it is to remember that inheritance is mechanism for
code reuse. Instead of writing the same thing over and over again we
can simply inherit from one class to another.
For this activity, you will write classes to represent different kinds of
homework assignments. Consider the following example of Math and
writing assignments.
Math Assignments
A Math assignment may need to store the student's name, the topic
(for example, "Fractions"), the textbook section (for example, "7.3"),
and the problems from that section (for example, "3-10, 20-21").
Writing Assignments
A writing assignment may need to store the student's name, the topic
(for example, "European History"), and the title of the assignment (for
example, "The Causes of World War II").
Sample Output
Samuel Bennett - Multiplication
2. Create this class and make sure to specify that it inherits from
the base Assignment class.
Sample Output
Roberto Rodriguez - Fractions
Section 7.3 Problems 8-19
3. Add the member variables and set up the constructor as you did
for the MathAssignment class.
To get the data you need for the method you can either make the
variable protected in the base class, or you can create a
public GetStudentName method to return it.
Sample Output
Mary Waters - European History
The Causes of World War II by Mary Waters
Sample Solution
The program ends with the user selecting the option “quit”.
Looking at the menu for the program can be a good place to start.
Take the time to go through each activity and discuss the way that
activity should work. What does it require the user to type in? What
does it display to the user?
The first step in designing a program like this is to think about the
classes you will need. When thinking about classes, it is often helpful
to consider the strong nouns in the program description.
BreathingActivity
ReflectingActivity
ListingActivity
Notice that these classes all pass the "is a" test, because a
Breathing activity is an activity, etc.
You might also to have a class to handle the menu and interaction, or
you might choose to handle this directly in your Main method in
the Program class.
Now that you have decided on the classes, you will need and their
responsibilities, the next step is to define the behaviors of these
classes. These will become methods for the class.
1. What are the behaviors this class will have in order to fulfill its
responsibilities? (In other words, what things should this
class do?)
The biggest trick here is that if any behavior is used by all the
activities then you should include it in the base class.
For example, each of the following are common behaviors that should
be in the base class:
Finally, there are behaviors for each activity that are completely
unique to that activity. For example, the ListActivity also needs to
provide behaviors for:
Activity
o DisplayStartingMessage() : void
o DisplayEndingMessage() : void
o ShowSpinner(seconds : int) : void
o ShowCountDown(second : int) : void
BreathingActivity
o Run() : void
ListingActivity
o Run() : void
o GetRandomPrompt() : string
o GetListFromUser() : List<string>
ReflectingActivity
o Run() : void
o GetRandomPrompt() : string
o GetRandomQuestion() : string
o DisplayPrompt() : void
o DisplayQuestions() : void
Now that you have defined the classes, their responsibilities, and their
behaviors, the next step is to determine what attributes the class
should have, or what variables it needs to store.
1. What attributes does this class need to fulfill its behaviors? (In
other words, what variables should this class store?)
Once again, you need to think about the attributes that are in
common and include them in the base class. Then, each derived class
may have its own unique attributes as well.
The description
The Breathing Activity likely does not need any attributes, but the
listing activity should store a count of the number of items listed, and
a list of prompts to draw from. Similarly, the Reflecting Activity should
store a list of questions and a list of prompts to draw from.
Activity
o _name : string
o _description : string
o _duration : int
BreathingActivity
o None needed
ListingActivity
o _count : int
o _prompts : List<string>
ReflectingActivity
o _prompts : List<string>
o _questions : List<string>
Define Constructors
Now that you have defined the classes, including their methods and
attributes, the next step is to think about the constructors that will be
used to create new instances of these classes. Remember that you
can create multiple constructors with different parameters to make it
easy to work with your classes.
The base class will need to initialize all of its member variables. You
might require them to be passed in as parameters or you might have
a constructor that sets some/all to default values to be changed later.
Then, the derived class constructor may be able to set good values in
the base class even if you don't pass parameters to it. For example, a
constructor that has no parameters could look like this:
public ReflectingActivity()
{
_name = "Reflecting";
_description = "This activity will help you reflect
on times ...";
_duration = 50;
The code above shows the most simple and straightforward way to do
this and assumes the variables are protected (not private) in the base
class. You could also use setters or pass them to the base base class
constructor directly.
The following is a final class diagram for each of the classes that you
can use as a guide as you being writing your code.
Conclude
At this point, you have the design of the classes you will need for this
project. If your design is not "perfect," or it needs to change as you
begin working on the project, that is just fine! As you learn more
details, you will naturally need to adjust your planning. This is why the
principles of programming with class are so valuable, because they
allow your program to easily change.
1. Determine who will be the lead student for the next meeting.
After the team activity, each person needs to individually do the the
following:
1. Open the project in VS Code. Create new files that contain the
"stubs" or empty code for all the classes, member variables,
and functions in your design.
Submission
We forget
We get busy
While it may not resolve all of the issues that keep people from taking
more time for reflection, a great program could help people by
providing structure and prompts to guide them through various
exercises.
The application could additional help the user keep track of the time
or frequency they spend in these activities and give them gentle
prompts and reminders.
5.3.3 Specification
Write a program that provides the three activities described above. It
should help them work through these activities in stages using basic
forms of delay (animation or countdown).
5.3.4Functional requirements
Your program must do the following:
Breathing activity
Reflection activity
o What made this time different than other times when you
were not as successful?
5. The user lists as many items as they can until they they reach
the duration specified by the user at the beginning.
6. The activity them displays back the number of items that were
entered.
For the core requirements you do not need to worry about the
following:
1. Your program does not need to track any statistics such as how
many times or how frequently the user has done an activity.
The following video demonstrates the way this program should work:
You might find the following code helps useful in this project:
Pausing
In the demo video, you can see the program pausing for a certain
period of time. This can be done with the Thread.Sleep() method
which takes an integer as the number of milliseconds for the current
"thread of execution" to sleep or pause.
The following example shows how to make the computer to wait for 1
second (1000 milliseconds):
Thread.Sleep(1000);
Console.WriteLine("I'm back!!");
Display Animations
Because the backspace character works like pressing the left arrow,
instead of a backspace, it does not delete the character on the
screen. With this in mind, it is common to write "\b \b" which moves
left, writes a blank space over the previous character and then moves
left again so it is ready for your new character.
Thread.Sleep(500);
The C# language has a powerful Date and Time library. You might find
it useful to get the current time, add a number of seconds to it, and
then check if the current time is less than the new time.
Thread.Sleep(3000);
The follow video shows how to use these code snippets to achieve
basic display animations.
5.3.10 Design
You will work with your team to create a design for this program.
Then, you will each write the code for the program individually.
For reference purposes, here is a copy of the design that was created
during the design activity.
In order to understand the decisions that led to this design, make sure
to walk through the design activity step by step before using this
design to start your code.
5.3.11Develop the program
In the course repository, find the Develop05 project in
the Prove folder and write your program there.
5.3.12 Submission
Method Overriding
An Example
// a parent class
public class Employee
{
private float salary = 100f;
But if the payroll system also has to account for hourly employees
that get paid a certain amount of money based on the number of
hours they worked. These employees are very similar to the standard
employee class, but they need different logic for
the CalculatePay method. This could be defined in a child class that
overrides the method from the Employee class. To do this, we first
mark the method in the base class with the keyword virtual which
tells C# that this method is eligible for another class to override it.
Then, in the child class, we use the keyword override as shown in
this example:
// a child class
public class HourlyEmployee : Employee
{
private float rate = 9f;
private float hours = 100f;
Output:
100
900
As stated, this exact same line of code can take on "many forms", or
more specifically, it will call different methods depending on the type
of the employee object encountered at run time.
The code that determines the manager may return may end up
returning either a base class Employee object or it may return
an HourlyEmployee object. Regardless of the type of employee
returned, the manager.CalculatePay() code will call the appropriate
method.
// a child class
public class SalaryEmployee : Employee
{
private float salary = 100f;
// a child class
public class HourlyEmployee : Employee
{
private float rate = 9f;
private float hours = 100f;
Take a moment and cast your mind back to the second principle of
programming with classes. One of the more important aspects of
applying encapsulation was to focus on what a class must do rather
than how it will do it. The same advice applies here.
Interfaces
Abstract methods give us a way to specify that a method must be
present in derived classes without providing a default
implementation. This idea is so powerful many times all we want to do
is define the public methods that a derived class must have--we do
not even want to provide any member variables or method bodies in
the base class.
A base class that only contains these abstract methods and nothing
else has a special name, it is called an Interface because it defines
the interface or public methods that any classes that implement it
must have. In this case, you define the "class" as an interface, and
then, you don't have to specify that the methods are abstract or
virtual or even public, because all of these things are implied.
Consider the following code:
6.1.6 In Summary
One of the recurring themes through all of this has been the
importance of focusing on class contracts or the interface. Identifying,
defining and developing them are of prime concern for those who
practice programming with classes on a regular basis.
For all shapes, you need to keep track of the color of the paper and
then have a method to compute the area. The area should not be
stored as a member variable, but instead, you should store the length
of the shapes sides and then compute the area as needed.
Your program should include squares (which store a color and a single
side), rectangles (which store a color and two sides), and a circle
(which store a color and a radius). You should create several kinds of
shapes and put them into a single list. Then, iterate through the list
and display their areas.
In this example all shapes have a color and a method to get the area,
but the implementation of that method will be different for each kind
of shape. Thus, the GetArea method should be declared in the base
class, but you should override it in the derived classes.
2. Add the color member variable and a getter and setter for it.
3. Create a constructor that accepts the color and the side, and
then call the base constructor with the color.
5. Override the GetArea() method from the base class and fill in
the body of this function to return the area.
1. Repeat the steps above for the Rectangle and Circle classes,
putting them each in their own files, storing the necessary
variables, and overriding the GetArea() for each.
2. Test these classes back in Main and make sure they work as
expected.
3. Iterate through the list of shapes. For each one, call and display
the GetColor() and GetArea() methods.
Sample Solution
Submission