SlideShare a Scribd company logo
1 of 55
Download to read offline
COMPSCI 121: BASIC METHODS & CLASSES
FALL 19
BYTE FROM COMPUTING HISTORY
Grace Hopper developed the
first computer language,
which eventually became
known as COBOL.
2
GOALS FOR TODAY’S CLASS
• Demo in JGRASP
•How classes work together
• Lecture
•More about Classes, Objects, Methods,
& Variables
3
IMPORTANT TO NOTE
Exam 1 covers content
from chapters 1 to 3.
You’ll get practice
worksheets and a
sample exam.
4
PIZZA PROJECT - DESIGN - T-P-S
1. What does
PizzaCalculator do?
2. What information does
PizzaMain send to /
receive from
PizzaCalculator? 5
PIZZA PROJECT DESIGN - T-P-S ANSWERS
1. What does PizzaCalculator do?
It calculates the volume and area of a pizza.
2. What information does PizzaMain send to /
receive from PizzaCalculator?
Sends: arguments for constructor and methods.
Receives: area of pizza.
6
The main class creates new instances of
PizzaCalculator.
The printPizzaVolume methods prints to the
console.
SNAPSHOT OF CLASS VARIABLES
7
New
instance
After calling
printPizza
Volume
method
SNAPSHOT OF CLASS VARIABLES
8
After calling
calculatePizzaArea methodNew instance
DEMO: PIZZA PROJECT
You saw
1. A class user need not know how the class' data and methods are
implemented, but need only understand how each public member
method behaves.
2. A programmer can create one or more objects of the same class
a. declare a reference variable of the class type.
b. assign the variable with an instance of the class type.
3. The new operator explicitly allocates an object of the specified
class type.
4. The "." operator is used to invoke a method on an object.
5. Within a member method, the implicitly-passed object reference
is accessible via the keyword this
9
REMINDER: MAIN METHOD
main() is a static method, which
means main() does not have direct
access to the class' instance members.
A programmer must create objects
within main() to call instance methods.
10
THE this. keyword
Using this makes clear that a class member is being accessed. Such use is
essential if a field member and parameter have the same identifier because
the parameter name dominates. 11
CLICKER QUESTION #1
A Car class (from last week) object is
instantiated:
Car myCar = new Car(13.5, 5.0);
Which one of the following correctly accesses
the fuel amount attribute of myCar?
A. myCar.fuelAmount;
B. myCar.getFuelAmount();
C. myCar.getFuel;
D. myCar.getFuel();
12
CLICKER QUESTION #1
A Car class (from last week) object is instantiated:
Car myCar = new Car(13.5, 5.0);
Which one of the following correctly accesses the fuel
amount attribute of myCar?
A. myCar.fuelAmount; private- can’t access
B. myCar.getFuelAmount(); not a method in Car class
C. myCar.getFuel; not a method call
D. myCar.getFuel(); CORRECT
13
CLICKER QUESTION #2
Given the method definition below, indicate which is a
valid return statement:
public int calculate(int num1, int num2)
{ ... }
A. return num1, num2;
B. return;
C. return num1 * num2;
D. return (num1, num2);
14
CLICKER QUESTION #2 ANSWER
Given the definition below, indicate which is a valid
return statement:
int calculate(int num1, int num2) { ... }
**A return statement can return only one value.
A. return num1, num2;**
B. return; must return int value
C. return num1 * num2; CORRECT
D. return (num1, num2);**
15
CLICKER QUESTION #3
16
Choose the incorrect statement
A. Creating methods helps main run faster.
B. Decomposing a program into methods aids
program readability.
C. A method can be defined once, then called
from multiple places in a program.
D. There can be only one main method in a
class.
CLICKER QUESTION #3 ANSWER
17
Choose the incorrect statement
A. Creating methods helps main run faster.
B. Decomposing a program into methods aids
program readability. CORRECT
C. A method can be defined once, then called from
multiple places in a program. CORRECT
D. There can be only one main method in a class.
CORRECT
More methods may cause slightly slower
program execution - but improve readability.
CLICKER QUESTION #4
Choose the incorrect statement/s
1. Only one constructor can be declared in a class.
2. A constructor must have a return type.
3. A constructor must have at least one parameter.
4. A constructor must be called to make an instance of the
class.
A. 1, 2, 3, 4
B. 1, 2, 3
C. 2, 3, 4
D. 1, 2 18
CLICKER QUESTION #4
Choose the incorrect statement/s
1. Only one constructor can be declared in a class. INCORRECT
2. A constructor must have a return type. INCORRECT
3. A constructor must have at least one parameter. INCORRECT
4. A constructor must be called to make an instance of the class.
CORRECT
A. 1, 2, 3, 4
B. 1, 2, 3
C. 2, 3, 4
D. 1, 2
19
INTRODUCTION TO STRING CLASS METHODS (1)
Strings are made up of characters. The characters in a
particular string hold fixed positions in that string,
beginning with position 0 and not at 1.
20
String pupName = “Spot”;
char ch = pupName.charAt(1);
// ch is assigned ‘p’
ch = pupName.charAt(0);
// ch  is assigned ‘S’
STRING CLASS METHODS (2)
Note: Strings are immutable – never change.
pupName is still “Spot”;
Some String methods need arguments.
String pupName = ”Spot";
int len = pupName.length();//len assigned 4
String huh = pupName.concat(“less”); //
Spotless
String bigHuh = pupName.toUpperCase();
//SPOT
21
JAVA API - STRING CLASS
https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/String.html
22
CLICKER QUESTION #5
Java's String class has a length() method that
returns the length of the string.
What is returned by the call to the length method below?
String greetingStr = "Hello";
greetingStr.length();
A. 7
B. 5
C. 8
D. 6
23
CLICKER QUESTION #5 ANSWER
Java's String class has a length() method that returns
the length of the string.
What is returned by the call to the length method below.
String greetingStr = "Hello";
greetingStr.length();
A. 7
B. 5
C. 8
D. 6
24
SUMMARY: PARAMETERS & ARGUMENTS
● Parameter: method input specified in method definition.
○ Upon a call, parameter's memory location is allocated, and
parameter is assigned with argument's value.
○ Upon return, parameter is deleted from memory.
○ Method definition may have multiple parameters, separated by
commas.
○ A method definition with no parameters must still have empty
parentheses()- the call must include parentheses, with no argument.
● Argument: value provided to method's parameter during method call.
○ Parameters are assigned with argument values by position: First
parameter with first argument, second with second, etc.
○
25
WEEK 3 TO-DO LIST:
• Check your iClicker grades in Moodle.
• Complete zyBook chapters 1-3 exercises (content for
exam)
• Download Lab 3 code before Friday and check that it
compiles - your group will not wait for you!
• Communicate with us using only Moodle forum or
Piazza.
2
6
COMPSCI 121: BASIC METHODS & CLASSES
contd.
FALL 19
GOALS FOR TODAY’S CLASS
• Demo of Project 2
• Lecture
• Testing - why and how
• Generating Javadocs
• Demo Javadocs
2
WHY AND HOW DO WE TEST?
A chef tastes food before serving.
1. Unit testing means to create and run a testbench
for a specific unit like a method of a class.
2. JUnit testbench tests a program with a series of
input/output checks known as test cases.
a. The testbench creates an object, then checks
public methods for correctness.
3
HOW TO WRITE YOUR OWN TESTS
1. Use System.out.print statements in the main class.
Remember to delete when submitting your project! (not a Unit test)
2. Do Unit testing: create and run a testbench for a specific item (or
"unit") like a method or a class. See zyBooks 3.7.
Note: uses if statements, that we have not covered as yet.
4
USING JUNIT
Regression testing: retest an item like a class anytime that item is
changed; if previously-passed test cases fail, the item has "regressed".
In the sample test given to you to check if JUnit is installed properly:.
5
THE SAMPLE TEST DETAILS
6
Message if
test fails
Expected
value from
test
Method
called for
actual value
In LAB 3, you’ll learn more about running tests
and how the Assert class methods work.
DETAILS OF PROJECT 2: Receipt Generator
To be released on Friday
Complete a program where a user can enter item
names and their respective prices, and it will calculate
the cumulative total, and print the list of items they
purchased along with their prices.
Input: a user can enter item names and their
respective prices,
Process: the program calculates the cumulative total
Output: it prints the total, as well as lists the items
purchased along with their prices. 7
DETAILS OF PROJECT 2: Receipt Generator
8
Has 2 classes and runs tests.
You need to download and configure JUnit files to run
the tests.
The user
interface
DESIGN OF PROJECT 2
Think of main class
as “front-end” and
other class as
“back-end”.
9
DEMO - PROJECT 2
Running the starter code
10
Running the tests
DEMO - PROJECT 2
Running the finished code
11
Running the tests
REVIEW: WHAT YOU SAW IN THE DEMO
1. Configure JUnit path in jGRASP
2. Download and unzip/extract the Project 2 zip file
3. Compile the files.
4. Run the main file.
5. Run the tests.
TO DO for PROJECT 2
1. Complete the tasks - see comments given to you.
2. Run the tests.
3. Upload in Gradescope as zip file.
4. Use the Debugger or ask us for help, if necessary.
12
JAVADOC TOOL
13
Documentation generated by Javadoc is known as Application
Programming Interface (API).
We use multi-line comments between the /** and */ characters.
We use tags to explain e.g. @author
GENERATING JAVADOCS
14
Private class members, which
cannot be accessed by other
classes, are not typically included
in the documentation.
VIEWING THE DOCS WITH LECTURE CODE
Opens in
browser.
15
UML DIAGRAM for
today’s DEMO
16
Class
Variables
Constructors
Methods
REVIEW
17
Returns information
Sends arguments for
constructors and
methods
WHAT WE SAW:
IMPLEMENTATION OF A CLASS (1)
18
Comments style
Visibility
(public/private)
Class variables
IMPLEMENTATION OF A CLASS (2)
19
Two
constructors
Initializing
variables
Use of this. parameters
Invokes first
constructor
IMPLEMENTING METHODS
20
parameters
variable value
return statement
assignment
void return
type
int return
type
method definition
method
block
USING THE MAIN METHOD
21
Creating instances of
ElapsedTime class
Sending arguments to
setTime methodmethod call
CLICKER QUESTION #1
Choose the correct statement
A. A private class member cannot be accessed as
this.classMember.
B. The 'this' keyword can be used in a constructor to
invoke a different constructor.
C. Using ‘this’ leads to confusion between class
members and parameter names.
22
CLICKER QUESTION #1 ANSWER
Choose the correct statement
A. A private class member cannot be accessed as this.classMember.
It can be accessed from within the same class.
B. The 'this' keyword can be used in a constructor to invoke a different
constructor.
Correct - see the lecture code
C. Using ‘this’ leads to confusion between class members and parameter
names.
Use "this" to distinguish the class member from the parameter name.
23
CLICKER QUESTION #2
In main(), given variable declaration:
ElapsedTime startTime = new
ElapsedTime();
Which statement sets startTime to hours
and minutes?
24
A. hours = 5; minutes = 30;
B. setTime.hours = 5;
setTime.minutes = 30;
C. this.setTime(int 5, int 10);
D. None of the above
CLICKER QUESTION #2 ANSWER
In main(), given variable declaration:
ElapsedTime startTime = new
ElapsedTime();
Which statement sets startTime to hours
and minutes?
25
A. hours = 5; minutes = 30; not accessible - private.
B. setTime.hours = 5; setTime.minutes = 30;
not accessible - private.
C. this.setTime(int 5, int 10); 'this' is only visible
within a method member, not in main().
D. None of the above
WRITING TESTS
• More practice with JUnit testing in LAB 3.
• Start thinking of writing your own tests.
• See figure 3.7.1 in zyBook section 3.7 for how to
write your own tests using a main method.
• Include not just typical values but also border
cases: Unusual or extreme test case values like 0,
negative numbers, or large numbers.
26
SUMMARY: HOW TO DEVELOP CODE
• Modular development: Divide a program into separate modules - develop and
test separately and then integrate into a single program.
• Incremental development: Write, compile, and test a small amount of code,
then write, compile, and test a small amount more, and so on.
• Method stub: Create a method definition whose statements have not yet been
written.
• Guidelines:
• Each method should have easily-recognizable behavior, and the behavior of
methods should be easily understandable via the sequence of method calls.
• A method's definition usually shouldn't have more than about 30 lines of
code.
• Regression testing: Retest a class anytime that class is changed.27
PREPARE FOR EXAM 1
1. Review from zyBooks chapters 1 to 3
(not the optional content).
2. Review Lecture slides.
3. Review Lab worksheets.
4. Review Project code.
5. Review exam prep worksheet in Moodle
28
WEEK 3 TO-DO LIST:
• Check your iClicker grades in Moodle.
• Complete zyBook chapter 1-3 exercises (content for
exam)
• Download and configure JUnit before the lab. There is
a Workshop tonight on JUnit and testing.
• Download Lab 3 code before the lab and check that it
compiles - your group will not wait for you!
• Communicate with us using only Moodle forum or
Piazza.
• Start Project 2 early - seek help in office hours. 2
9

More Related Content

Similar to Chapter 3

Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMSJustinHolt20
 
Cis 355 ilab 1 of 6
Cis 355 ilab 1 of 6Cis 355 ilab 1 of 6
Cis 355 ilab 1 of 6comp274
 
Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6solutionjug4
 
Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6helpido9
 
Cis247 a ilab 1 of 7 creating a user interface
Cis247 a ilab 1 of 7 creating a user interfaceCis247 a ilab 1 of 7 creating a user interface
Cis247 a ilab 1 of 7 creating a user interfacecis247
 
Cis247 i lab 1 of 7 creating a user interface
Cis247 i lab 1 of 7 creating a user interfaceCis247 i lab 1 of 7 creating a user interface
Cis247 i lab 1 of 7 creating a user interfacesdjdskjd9097
 
International Institute of technology (android)
International Institute of technology (android)International Institute of technology (android)
International Institute of technology (android)Nazih Heni
 
Cis247 i lab 1 of 7 creating a user interface
Cis247 i lab 1 of 7 creating a user interfaceCis247 i lab 1 of 7 creating a user interface
Cis247 i lab 1 of 7 creating a user interfacesdjdskjd9097
 
Cis247 a ilab 1 of 7 creating a user interface
Cis247 a ilab 1 of 7 creating a user interfaceCis247 a ilab 1 of 7 creating a user interface
Cis247 a ilab 1 of 7 creating a user interfaceccis224477
 
Project3build.xml Builds, tests, and runs the project .docx
Project3build.xml      Builds, tests, and runs the project .docxProject3build.xml      Builds, tests, and runs the project .docx
Project3build.xml Builds, tests, and runs the project .docxwoodruffeloisa
 
Cmis 102 Effective Communication / snaptutorial.com
Cmis 102  Effective Communication / snaptutorial.comCmis 102  Effective Communication / snaptutorial.com
Cmis 102 Effective Communication / snaptutorial.comHarrisGeorg12
 
Cmis 102 Enthusiastic Study / snaptutorial.com
Cmis 102 Enthusiastic Study / snaptutorial.comCmis 102 Enthusiastic Study / snaptutorial.com
Cmis 102 Enthusiastic Study / snaptutorial.comStephenson22
 
Cmis 102 Success Begins / snaptutorial.com
Cmis 102 Success Begins / snaptutorial.comCmis 102 Success Begins / snaptutorial.com
Cmis 102 Success Begins / snaptutorial.comWilliamsTaylorza48
 
Devry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees newDevry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees newmailemail
 
Devry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees newDevry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees newolivergeorg
 
Devry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees newDevry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees newuopassignment
 
Devry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees newDevry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees newmybrands2
 
Module 2: C# 3.0 Language Enhancements (Material)
Module 2: C# 3.0 Language Enhancements (Material)Module 2: C# 3.0 Language Enhancements (Material)
Module 2: C# 3.0 Language Enhancements (Material)Mohamed Saleh
 

Similar to Chapter 3 (20)

Week 2
Week 2Week 2
Week 2
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMS
 
Cis 355 ilab 1 of 6
Cis 355 ilab 1 of 6Cis 355 ilab 1 of 6
Cis 355 ilab 1 of 6
 
Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6
 
Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6
 
Cis247 a ilab 1 of 7 creating a user interface
Cis247 a ilab 1 of 7 creating a user interfaceCis247 a ilab 1 of 7 creating a user interface
Cis247 a ilab 1 of 7 creating a user interface
 
Cis247 i lab 1 of 7 creating a user interface
Cis247 i lab 1 of 7 creating a user interfaceCis247 i lab 1 of 7 creating a user interface
Cis247 i lab 1 of 7 creating a user interface
 
International Institute of technology (android)
International Institute of technology (android)International Institute of technology (android)
International Institute of technology (android)
 
Cis247 i lab 1 of 7 creating a user interface
Cis247 i lab 1 of 7 creating a user interfaceCis247 i lab 1 of 7 creating a user interface
Cis247 i lab 1 of 7 creating a user interface
 
Cis247 a ilab 1 of 7 creating a user interface
Cis247 a ilab 1 of 7 creating a user interfaceCis247 a ilab 1 of 7 creating a user interface
Cis247 a ilab 1 of 7 creating a user interface
 
Project3build.xml Builds, tests, and runs the project .docx
Project3build.xml      Builds, tests, and runs the project .docxProject3build.xml      Builds, tests, and runs the project .docx
Project3build.xml Builds, tests, and runs the project .docx
 
Cmis 102 Effective Communication / snaptutorial.com
Cmis 102  Effective Communication / snaptutorial.comCmis 102  Effective Communication / snaptutorial.com
Cmis 102 Effective Communication / snaptutorial.com
 
Cmis 102 Enthusiastic Study / snaptutorial.com
Cmis 102 Enthusiastic Study / snaptutorial.comCmis 102 Enthusiastic Study / snaptutorial.com
Cmis 102 Enthusiastic Study / snaptutorial.com
 
Cmis 102 Success Begins / snaptutorial.com
Cmis 102 Success Begins / snaptutorial.comCmis 102 Success Begins / snaptutorial.com
Cmis 102 Success Begins / snaptutorial.com
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
Devry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees newDevry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees new
 
Devry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees newDevry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees new
 
Devry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees newDevry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees new
 
Devry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees newDevry ecet 370 week 6 ilab binary trees new
Devry ecet 370 week 6 ilab binary trees new
 
Module 2: C# 3.0 Language Enhancements (Material)
Module 2: C# 3.0 Language Enhancements (Material)Module 2: C# 3.0 Language Enhancements (Material)
Module 2: C# 3.0 Language Enhancements (Material)
 

More from EasyStudy3

2. polynomial interpolation
2. polynomial interpolation2. polynomial interpolation
2. polynomial interpolationEasyStudy3
 
Chapter2 slides-part 2-harish complete
Chapter2 slides-part 2-harish completeChapter2 slides-part 2-harish complete
Chapter2 slides-part 2-harish completeEasyStudy3
 
Chapter 12 vectors and the geometry of space merged
Chapter 12 vectors and the geometry of space mergedChapter 12 vectors and the geometry of space merged
Chapter 12 vectors and the geometry of space mergedEasyStudy3
 
Chapter 5 gen chem
Chapter 5 gen chemChapter 5 gen chem
Chapter 5 gen chemEasyStudy3
 
Topic 4 gen chem guobi
Topic 4 gen chem guobiTopic 4 gen chem guobi
Topic 4 gen chem guobiEasyStudy3
 
Gen chem topic 3 guobi
Gen chem topic 3  guobiGen chem topic 3  guobi
Gen chem topic 3 guobiEasyStudy3
 
Gen chem topic 1 guobi
Gen chem topic 1 guobiGen chem topic 1 guobi
Gen chem topic 1 guobiEasyStudy3
 

More from EasyStudy3 (20)

Week 7
Week 7Week 7
Week 7
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Week 6
Week 6Week 6
Week 6
 
2. polynomial interpolation
2. polynomial interpolation2. polynomial interpolation
2. polynomial interpolation
 
Chapter2 slides-part 2-harish complete
Chapter2 slides-part 2-harish completeChapter2 slides-part 2-harish complete
Chapter2 slides-part 2-harish complete
 
L6
L6L6
L6
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
2
22
2
 
Lec#4
Lec#4Lec#4
Lec#4
 
Chapter 12 vectors and the geometry of space merged
Chapter 12 vectors and the geometry of space mergedChapter 12 vectors and the geometry of space merged
Chapter 12 vectors and the geometry of space merged
 
Week 5
Week 5Week 5
Week 5
 
Chpater 6
Chpater 6Chpater 6
Chpater 6
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Lec#3
Lec#3Lec#3
Lec#3
 
Chapter 16 2
Chapter 16 2Chapter 16 2
Chapter 16 2
 
Chapter 5 gen chem
Chapter 5 gen chemChapter 5 gen chem
Chapter 5 gen chem
 
Topic 4 gen chem guobi
Topic 4 gen chem guobiTopic 4 gen chem guobi
Topic 4 gen chem guobi
 
Gen chem topic 3 guobi
Gen chem topic 3  guobiGen chem topic 3  guobi
Gen chem topic 3 guobi
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Gen chem topic 1 guobi
Gen chem topic 1 guobiGen chem topic 1 guobi
Gen chem topic 1 guobi
 

Recently uploaded

Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 

Recently uploaded (20)

INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 

Chapter 3

  • 1. COMPSCI 121: BASIC METHODS & CLASSES FALL 19
  • 2. BYTE FROM COMPUTING HISTORY Grace Hopper developed the first computer language, which eventually became known as COBOL. 2
  • 3. GOALS FOR TODAY’S CLASS • Demo in JGRASP •How classes work together • Lecture •More about Classes, Objects, Methods, & Variables 3
  • 4. IMPORTANT TO NOTE Exam 1 covers content from chapters 1 to 3. You’ll get practice worksheets and a sample exam. 4
  • 5. PIZZA PROJECT - DESIGN - T-P-S 1. What does PizzaCalculator do? 2. What information does PizzaMain send to / receive from PizzaCalculator? 5
  • 6. PIZZA PROJECT DESIGN - T-P-S ANSWERS 1. What does PizzaCalculator do? It calculates the volume and area of a pizza. 2. What information does PizzaMain send to / receive from PizzaCalculator? Sends: arguments for constructor and methods. Receives: area of pizza. 6 The main class creates new instances of PizzaCalculator. The printPizzaVolume methods prints to the console.
  • 7. SNAPSHOT OF CLASS VARIABLES 7 New instance After calling printPizza Volume method
  • 8. SNAPSHOT OF CLASS VARIABLES 8 After calling calculatePizzaArea methodNew instance
  • 9. DEMO: PIZZA PROJECT You saw 1. A class user need not know how the class' data and methods are implemented, but need only understand how each public member method behaves. 2. A programmer can create one or more objects of the same class a. declare a reference variable of the class type. b. assign the variable with an instance of the class type. 3. The new operator explicitly allocates an object of the specified class type. 4. The "." operator is used to invoke a method on an object. 5. Within a member method, the implicitly-passed object reference is accessible via the keyword this 9
  • 10. REMINDER: MAIN METHOD main() is a static method, which means main() does not have direct access to the class' instance members. A programmer must create objects within main() to call instance methods. 10
  • 11. THE this. keyword Using this makes clear that a class member is being accessed. Such use is essential if a field member and parameter have the same identifier because the parameter name dominates. 11
  • 12. CLICKER QUESTION #1 A Car class (from last week) object is instantiated: Car myCar = new Car(13.5, 5.0); Which one of the following correctly accesses the fuel amount attribute of myCar? A. myCar.fuelAmount; B. myCar.getFuelAmount(); C. myCar.getFuel; D. myCar.getFuel(); 12
  • 13. CLICKER QUESTION #1 A Car class (from last week) object is instantiated: Car myCar = new Car(13.5, 5.0); Which one of the following correctly accesses the fuel amount attribute of myCar? A. myCar.fuelAmount; private- can’t access B. myCar.getFuelAmount(); not a method in Car class C. myCar.getFuel; not a method call D. myCar.getFuel(); CORRECT 13
  • 14. CLICKER QUESTION #2 Given the method definition below, indicate which is a valid return statement: public int calculate(int num1, int num2) { ... } A. return num1, num2; B. return; C. return num1 * num2; D. return (num1, num2); 14
  • 15. CLICKER QUESTION #2 ANSWER Given the definition below, indicate which is a valid return statement: int calculate(int num1, int num2) { ... } **A return statement can return only one value. A. return num1, num2;** B. return; must return int value C. return num1 * num2; CORRECT D. return (num1, num2);** 15
  • 16. CLICKER QUESTION #3 16 Choose the incorrect statement A. Creating methods helps main run faster. B. Decomposing a program into methods aids program readability. C. A method can be defined once, then called from multiple places in a program. D. There can be only one main method in a class.
  • 17. CLICKER QUESTION #3 ANSWER 17 Choose the incorrect statement A. Creating methods helps main run faster. B. Decomposing a program into methods aids program readability. CORRECT C. A method can be defined once, then called from multiple places in a program. CORRECT D. There can be only one main method in a class. CORRECT More methods may cause slightly slower program execution - but improve readability.
  • 18. CLICKER QUESTION #4 Choose the incorrect statement/s 1. Only one constructor can be declared in a class. 2. A constructor must have a return type. 3. A constructor must have at least one parameter. 4. A constructor must be called to make an instance of the class. A. 1, 2, 3, 4 B. 1, 2, 3 C. 2, 3, 4 D. 1, 2 18
  • 19. CLICKER QUESTION #4 Choose the incorrect statement/s 1. Only one constructor can be declared in a class. INCORRECT 2. A constructor must have a return type. INCORRECT 3. A constructor must have at least one parameter. INCORRECT 4. A constructor must be called to make an instance of the class. CORRECT A. 1, 2, 3, 4 B. 1, 2, 3 C. 2, 3, 4 D. 1, 2 19
  • 20. INTRODUCTION TO STRING CLASS METHODS (1) Strings are made up of characters. The characters in a particular string hold fixed positions in that string, beginning with position 0 and not at 1. 20 String pupName = “Spot”; char ch = pupName.charAt(1); // ch is assigned ‘p’ ch = pupName.charAt(0); // ch  is assigned ‘S’
  • 21. STRING CLASS METHODS (2) Note: Strings are immutable – never change. pupName is still “Spot”; Some String methods need arguments. String pupName = ”Spot"; int len = pupName.length();//len assigned 4 String huh = pupName.concat(“less”); // Spotless String bigHuh = pupName.toUpperCase(); //SPOT 21
  • 22. JAVA API - STRING CLASS https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/String.html 22
  • 23. CLICKER QUESTION #5 Java's String class has a length() method that returns the length of the string. What is returned by the call to the length method below? String greetingStr = "Hello"; greetingStr.length(); A. 7 B. 5 C. 8 D. 6 23
  • 24. CLICKER QUESTION #5 ANSWER Java's String class has a length() method that returns the length of the string. What is returned by the call to the length method below. String greetingStr = "Hello"; greetingStr.length(); A. 7 B. 5 C. 8 D. 6 24
  • 25. SUMMARY: PARAMETERS & ARGUMENTS ● Parameter: method input specified in method definition. ○ Upon a call, parameter's memory location is allocated, and parameter is assigned with argument's value. ○ Upon return, parameter is deleted from memory. ○ Method definition may have multiple parameters, separated by commas. ○ A method definition with no parameters must still have empty parentheses()- the call must include parentheses, with no argument. ● Argument: value provided to method's parameter during method call. ○ Parameters are assigned with argument values by position: First parameter with first argument, second with second, etc. ○ 25
  • 26. WEEK 3 TO-DO LIST: • Check your iClicker grades in Moodle. • Complete zyBook chapters 1-3 exercises (content for exam) • Download Lab 3 code before Friday and check that it compiles - your group will not wait for you! • Communicate with us using only Moodle forum or Piazza. 2 6
  • 27. COMPSCI 121: BASIC METHODS & CLASSES contd. FALL 19
  • 28. GOALS FOR TODAY’S CLASS • Demo of Project 2 • Lecture • Testing - why and how • Generating Javadocs • Demo Javadocs 2
  • 29. WHY AND HOW DO WE TEST? A chef tastes food before serving. 1. Unit testing means to create and run a testbench for a specific unit like a method of a class. 2. JUnit testbench tests a program with a series of input/output checks known as test cases. a. The testbench creates an object, then checks public methods for correctness. 3
  • 30. HOW TO WRITE YOUR OWN TESTS 1. Use System.out.print statements in the main class. Remember to delete when submitting your project! (not a Unit test) 2. Do Unit testing: create and run a testbench for a specific item (or "unit") like a method or a class. See zyBooks 3.7. Note: uses if statements, that we have not covered as yet. 4
  • 31. USING JUNIT Regression testing: retest an item like a class anytime that item is changed; if previously-passed test cases fail, the item has "regressed". In the sample test given to you to check if JUnit is installed properly:. 5
  • 32. THE SAMPLE TEST DETAILS 6 Message if test fails Expected value from test Method called for actual value In LAB 3, you’ll learn more about running tests and how the Assert class methods work.
  • 33. DETAILS OF PROJECT 2: Receipt Generator To be released on Friday Complete a program where a user can enter item names and their respective prices, and it will calculate the cumulative total, and print the list of items they purchased along with their prices. Input: a user can enter item names and their respective prices, Process: the program calculates the cumulative total Output: it prints the total, as well as lists the items purchased along with their prices. 7
  • 34. DETAILS OF PROJECT 2: Receipt Generator 8 Has 2 classes and runs tests. You need to download and configure JUnit files to run the tests. The user interface
  • 35. DESIGN OF PROJECT 2 Think of main class as “front-end” and other class as “back-end”. 9
  • 36. DEMO - PROJECT 2 Running the starter code 10 Running the tests
  • 37. DEMO - PROJECT 2 Running the finished code 11 Running the tests
  • 38. REVIEW: WHAT YOU SAW IN THE DEMO 1. Configure JUnit path in jGRASP 2. Download and unzip/extract the Project 2 zip file 3. Compile the files. 4. Run the main file. 5. Run the tests. TO DO for PROJECT 2 1. Complete the tasks - see comments given to you. 2. Run the tests. 3. Upload in Gradescope as zip file. 4. Use the Debugger or ask us for help, if necessary. 12
  • 39. JAVADOC TOOL 13 Documentation generated by Javadoc is known as Application Programming Interface (API). We use multi-line comments between the /** and */ characters. We use tags to explain e.g. @author
  • 40. GENERATING JAVADOCS 14 Private class members, which cannot be accessed by other classes, are not typically included in the documentation.
  • 41. VIEWING THE DOCS WITH LECTURE CODE Opens in browser. 15
  • 42. UML DIAGRAM for today’s DEMO 16 Class Variables Constructors Methods
  • 43. REVIEW 17 Returns information Sends arguments for constructors and methods
  • 44. WHAT WE SAW: IMPLEMENTATION OF A CLASS (1) 18 Comments style Visibility (public/private) Class variables
  • 45. IMPLEMENTATION OF A CLASS (2) 19 Two constructors Initializing variables Use of this. parameters Invokes first constructor
  • 46. IMPLEMENTING METHODS 20 parameters variable value return statement assignment void return type int return type method definition method block
  • 47. USING THE MAIN METHOD 21 Creating instances of ElapsedTime class Sending arguments to setTime methodmethod call
  • 48. CLICKER QUESTION #1 Choose the correct statement A. A private class member cannot be accessed as this.classMember. B. The 'this' keyword can be used in a constructor to invoke a different constructor. C. Using ‘this’ leads to confusion between class members and parameter names. 22
  • 49. CLICKER QUESTION #1 ANSWER Choose the correct statement A. A private class member cannot be accessed as this.classMember. It can be accessed from within the same class. B. The 'this' keyword can be used in a constructor to invoke a different constructor. Correct - see the lecture code C. Using ‘this’ leads to confusion between class members and parameter names. Use "this" to distinguish the class member from the parameter name. 23
  • 50. CLICKER QUESTION #2 In main(), given variable declaration: ElapsedTime startTime = new ElapsedTime(); Which statement sets startTime to hours and minutes? 24 A. hours = 5; minutes = 30; B. setTime.hours = 5; setTime.minutes = 30; C. this.setTime(int 5, int 10); D. None of the above
  • 51. CLICKER QUESTION #2 ANSWER In main(), given variable declaration: ElapsedTime startTime = new ElapsedTime(); Which statement sets startTime to hours and minutes? 25 A. hours = 5; minutes = 30; not accessible - private. B. setTime.hours = 5; setTime.minutes = 30; not accessible - private. C. this.setTime(int 5, int 10); 'this' is only visible within a method member, not in main(). D. None of the above
  • 52. WRITING TESTS • More practice with JUnit testing in LAB 3. • Start thinking of writing your own tests. • See figure 3.7.1 in zyBook section 3.7 for how to write your own tests using a main method. • Include not just typical values but also border cases: Unusual or extreme test case values like 0, negative numbers, or large numbers. 26
  • 53. SUMMARY: HOW TO DEVELOP CODE • Modular development: Divide a program into separate modules - develop and test separately and then integrate into a single program. • Incremental development: Write, compile, and test a small amount of code, then write, compile, and test a small amount more, and so on. • Method stub: Create a method definition whose statements have not yet been written. • Guidelines: • Each method should have easily-recognizable behavior, and the behavior of methods should be easily understandable via the sequence of method calls. • A method's definition usually shouldn't have more than about 30 lines of code. • Regression testing: Retest a class anytime that class is changed.27
  • 54. PREPARE FOR EXAM 1 1. Review from zyBooks chapters 1 to 3 (not the optional content). 2. Review Lecture slides. 3. Review Lab worksheets. 4. Review Project code. 5. Review exam prep worksheet in Moodle 28
  • 55. WEEK 3 TO-DO LIST: • Check your iClicker grades in Moodle. • Complete zyBook chapter 1-3 exercises (content for exam) • Download and configure JUnit before the lab. There is a Workshop tonight on JUnit and testing. • Download Lab 3 code before the lab and check that it compiles - your group will not wait for you! • Communicate with us using only Moodle forum or Piazza. • Start Project 2 early - seek help in office hours. 2 9