30 Pages

Classes

Course: CIS 3900, Fall 2009
School: N.E. Illinois
Rating:
 
 
 
 
 

Word Count: 1031

Document Preview

Programming: Java From the Beginning Chapter 3: Classes and Objects 1-1 Objects Represent a physical object Have two properties State Contains one or more items of information Fields or variables Behavior Responds to operations that are performed on it May change the state of the object 1-2 Example of an Object Retractable ball-point pen State Variables Pen exposed (boolean: true or false) Ink...

Register Now

Unformatted Document Excerpt

Coursehero >> Illinois >> N.E. Illinois >> CIS 3900

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
Programming: Java From the Beginning Chapter 3: Classes and Objects 1-1 Objects Represent a physical object Have two properties State Contains one or more items of information Fields or variables Behavior Responds to operations that are performed on it May change the state of the object 1-2 Example of an Object Retractable ball-point pen State Variables Pen exposed (boolean: true or false) Ink supply (float) Behavior Operations (methods) Press button to expose/not expose pen Replace ink (add to ink supply) Determine how much ink remains Write (use ink) 1-3 Bank Loan Object State Variables Principal Duration Interest Rate Current Balance Interest Collected (to date) Behavior Operations (methods) Initiate a loan (construct a loan) including computation of payment Charge interest Make a payment (amortization schedule) Print totals 1-4 Objects Write a class definition Write the methods The class/methods are not executed until "called" from another program 1-5 Class definition public class ClassName { variables constructors methods } 1-6 Class Definition of a LoanObject public class LoanObject { // variables double principal; double interest; int months; double balance; double totalInterest; . . . } 1-7 Class Definition of a LoanObject Constructors Creates an Instance of the Object Creating a loan A program calls the constructor when a "loan" is created Usually passes values of the parameters Java Creates a Default Constructor if no parameters are passed Default Constructor can be overridden in the Class 1-8 Default Constructor public LoanObject () // () indicates no parameters are passed { principal = 0.0; interest = 0.0; months = 0; balance = 0.0; totalInterest = 0.0 payment = 0.0 } 1-9 Other Constructors Generally receive parameters from the calling program Creating/Constructing a Loan Parameters: double principal double interest (yearly rate) int years Parameters are also called arguments 1-10 Other Constructors public LoanObject (double argPrin, double argInterest, int argYears) // (arguments go inside the parenthesis) { principal = argPrin; interest =(argInterest / 12.0) * .01; months = argYears * 12 ; balance = argPrin; totalInterest = 0.0 payment = principal * interest / (1 Math.pow(... } 1-11 Create an Instance of the Object Code goes in the Calling Program Do NOT put this code in the CLASS double interest; double principal; int years; String strPrincipal = JOptionPane.showInputDialog ("enter principal") principal = Double.parseDouble(strPrincipal); String strInterest = JOptionPane.showInputDialog ("interest rate?"); interest = Double.parseDouble(strInterest); String strYrs = JopetionPane.showInputDialog ("Number of years?"); years = Integer.parseInt(strYrs); LoanObject LO1 = new LoanObject (principal, interest, years); // yearly interest rate 1-12 Explanation of the Constructor Call LoanObject LO1 = new LoanObject (principal, interest, years); /* LoanObject is the name of the class LO1 is an instance of the Loan Object -- it is ONE Loan LO1 is a variable name that I created new == calls the constructor named LoanObject three parameters -- double double integer --> calls the constructor with three parameters double double integer --> error or default constructor if there is no constructor with arguments double double integer */ 1-13 Method/Constructor Overloading Generally there are multiple constructors Different argument lists Known as Constructor Overloading 1-14 Class/Instance Methods Back to the Class Definition LoanObjects Methods (refer back to slide 4) Charge Interest Make a Payment (amortization schedule) Print Loan Statistics 1-15 Charge Interest Method public double interest () { double newBalance = (1 + Interest) * balance; int integerBalance (int) = Math.round(newBalance * 100); newBalance = integerBalance / 100.00; return newBalance; } 1-16 Charge Interest Method public double interest () { double newBalance = (1 + Interest) * balance; . . return newBalance; } Public double interest () --> no parameters are passed --> () --> one parameter is returned to the calling program. It is a double. Return newBalance 1-17 Other Methods makePayment printTotals getPayment setPayment The last two methods were used 1) as an example of a getter and setter method and 2) without them the payment that would print would be the last payment which is generally only a partial payment (see if statement) are available on the class handout also available at my web site. 1-18 Loan Example The Class Definition does not execute anything. But it must be compiled The java program calls the Class constructor and methods. Only one loan is created in this example. Value of the Object/Class definition is not fully realized until we get into arrays and/or data files If you do not compile the class definition, the java program will automatically compile it when you compile the calling program. Syntax errors received from the calling program can be confusing because the error may be from the class. I suggest you compile the class separately. 1-19 How Objects Are Stored LoanObject LO1; LO1 LoanObject LO1 = new LoanObject(150000, 12, 30); Loan Object LO1 Principal = 150000. Interest = .01 Months = 360 Balance = 150000. totalInterest = 0 1-20 LoanObjects LO1stores the location/address of the object A pointer variable (in C/C++) AKA a reference variable (in Java) 1-21 How Objects Are Stored LoanObject LO1 = new LoanObject(150000, 12, 30); LoanObject LO2 = LO1 Loan Object LO1 Principal = 150000. Interest = .01 Months = 360 Balance = 150000. LO2 totalInterest = 0 1-22 LoanObjects Previous Slide: LO1 and LO2 are two references/pointers They point to the same object There is only one object, but two pointers to it. To create two objects you need two calls to the constructor LoanObject LO1 = new LoanObject(...) LoanObject LO2 = new LoanObject(...) 1-23 LoanObjects LoanObject LO1 = new LoanObject(150000.0, 12.0, 30) LoanObject LO2 = new LoanObject(10000.0, 24.0, 20) Loan Object Principal = 150000. Interest = .1 Months = 360 Balance = 150000. totalInterest = 0 LO1 Loan Object Principal = 10000. Interest = .2 LO2 Months = 240 Balance = 10000. totalInterest = 0 1-24 LoanObjects LoanObject LO1 = new LoanObject(150000.0, 12.0, 30) LoanObject LO2 = new LoanObject(10000.0, 24.0, 20) LO1 = LO2 Loan Object Principal = 150000. Interest = .1 Months = 360 Balance = 150000. totalInterest = 0 LO1 Loan Object Principal = 10000. Interest = .2 LO2 Months = 240 Balance = 10000. totalInterest = 0 1-25 Notes on Previous Slide The top LoanObject is garbage Once an object has no pointer to it it becomes garbage Will not be able to be referenced again Java has automatic garbage collection Object will be deleted.Memory will be reused. 1-26 Section 3.8 Developing a Fraction Class A nice example of another class file Please read it 1-27 Getters and Setters These two instance methods are widely used. A getter method is called from the calling program to set one (or more) of the instance variables. It changes the value of a class variable. A setter method returns a value for one of the instance variables so that the calling program can use the variable. 1-28 Printing an Object Print the class variables Include an instance method named toString to print the object Example: Public String toString () { return "Original Principal: " + principal; } 1-29 Printing an Object To print an Object In the calling program System.out.println(LO1); This statement will call the toString method in the LoanObject Class. 1-30
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

N.E. Illinois - UX - 5250
The Normal ECGNormal P Wave NegativeinaVR PositiveinII 2.5mminamplitude <0.12sec.inwidthNormal P WaveNormaldirectionofatrial depolarizationaVR?II?Figures42and43Abnormal P WaveDirectionofatrialdepolarization withjunctionrhythmaVR?
N.E. Illinois - UX - 5250
Ventricular Conduction DisturbancesChapter 7Bundle Branches Normal conduction speed through the bundles is about 0.1 seconds.Bundle Branch Block Consider a blocked or slowed branch or bundleRight Bundle Branch BlockRight Bundle Branch Blo
N.E. Illinois - UX - 1
Economics 303 Spring 2008 Dr. Dao Problem Set 6(practice for Exam II)Name_Mary Tsai is paid $3,000 every 30 days. Her salary is deposited directly in her bank. She spends all her money at a constant rate over the 30 days and must pay cash. She c
N.E. Illinois - MARCH - 3
Students, We've been having a few problems that probably should be addressed. Please make sure and read this and ask if you have any questions. Understand that the computers are the Libraries equipment. Continually downloading material can cause soft
N.E. Illinois - UX - 4900
The Physiology of Marathon Running"The difference between the mile and the marathon is the difference between burning your fingers with a match and being slowly roasted over hot coals" Hal Higdon From a physiological standpoint running a marathon
N.E. Illinois - UX - 5230
Measuring Energy ExpenditureMeasuring the Energy Costs of ExerciseDirect calorimetrymeasures the body's heat production to calculate energy expenditure. Indirect calorimetrycalculates energy expenditure from the respiratory exchange ratio (RER
N.E. Illinois - UX - 4340
PED 4340 Exercise Physiology TERMS FOR FINAL EXAM Below is a list of 39 terms, 25 of which will be used on the final exam in a matching format. The 25 terms will listed along with 30 definitions or phrases that describe the terms, therefore, not all
N.E. Illinois - UX - 2440
The Hip JointExercises and InjuriesPelvis Abnormalities To appreciate the abnormalities that mayoccur, picture a box around the pelvis. The two most common situations are:1.the pelvis is tilted forward (anterior tilt); slightly rotate th
N.E. Illinois - UX - 3425
Stress and strain Can cause you pain, Take this course To save remorse.Kutna Hora, Czechoslovakia - building damaged by subsidence due to mining (photo fromLegget, 1973)Stress and Strainstress and strain compressive, tensile and shear balance o
N.E. Illinois - UX - 4101
K. Bower EIU 4101EIU 4101 Spaceship Earth Vocabulary Introduction Analytic thinking Controlled studies Creative thinking Critical thinking Environment Environmental science Hypothesis Geologic time scale Gross National Product Hypothesis Logical th
N.E. Illinois - UX - 1
29. The Organic Chemistry of Metabolic PathwaysBased on McMurry's Organic Chemistry, 6th edition2003 Ronald Kluger Department of Chemistry University of Toronto29.1 An Overview of Metabolism and Biochemical Energy Metabolism: The reactions in or
N.E. Illinois - UX - 1
Name_Quizwork #9 Chem 2430Assigned 10/25/05. Due 10/28/05 at 11 AM.As with all quizwork, this must be done completely. Two problems will be graded on this quizwork. If you leave any problem blank or incomplete, you will lose double the points fo
N.E. Illinois - GEG - 3050
Geography of Africa Paper AssignmentGeography of Africa Fall 2007AssignmentEach student will:Select a country to research Paper may be:A geographical overview of a country Research on a particular issue within their countryGeneral Fo
Wisconsin Milwaukee - CS - 424
The Big Picture: Where are We Now?Processor Control Datapath Processor Output Memory Input Input Control DatapathOutput MemoryMultiprocessor multiple processors with a single shared address space Cluster multiple computers (each with their o
Wisconsin Milwaukee - CS - 424
Review: Datapath with Data Hazard ControlPCSrc ID/EX.MemRead EX/MEMrite ID.W IF/Hazard UnitID/EXrite PC.W0 1IF/ID Add Control 04Shift left 2AddBranchMEM/WBInstruction MemoryRead Address PCRead Addr 1Data 1 Read Addr 2 Wri
Wisconsin Milwaukee - CS - 526
Discrete-Event Simulation: A First CourseSteve Park and Larry Leemis College of William and MaryTechnical Attractions of * Simulation Ability to compress time, expand time Ability to control sources of variation Avoids errors in measurement
Wisconsin Milwaukee - CS - 424
Ch 5: Designing a Single Cycle DatapathComputer Systems Architecture CS 424/524The Big Picture: Where are We Now? The Five Classic Components of a ComputerProcessor Input Control Datapath Memory Output Today's Topic: Design a Single Cycle Pro
Wisconsin Milwaukee - CS - 141
Chapter 11RecursionRecursion Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems Chapter 11 focuses on: thinking in a recursive manner programming in a recursive manner the correct
Wisconsin Milwaukee - CS - 131
Machine Language Day 10CSci 131 Oct. 3, 200604/30/09 1Outline Review Tracing Programs Building Programs Bit masking04/30/09 2Our Machine04/30/09 3Machine Language04/30/09 4Add numbers in memory cells 0D and 0E
Wisconsin Milwaukee - CS - 241
Lists and the Collection InterfaceChapter 4Chapter Objectives To become familiar with the List interface To understand how to write an array-based implementation of the List interface To study the difference between single-, double-, and circul
Wisconsin Milwaukee - CS - 241
CS 241 - Project3 Grading BreakdownCorrectness: 70% Execution Method DefinitionTesting: 20% Test Java file Test planStyle/Documentation/Submission 10%Specifically the methods from the f
Wisconsin Milwaukee - CS - 141
Chapter 7ArraysArrays Arrays are objects that help us organize large amounts of information Chapter 7 focuses on: array declaration and use bounds checking and capacity arrays that store object references variable length parameter lists
Wisconsin Milwaukee - CS - 141
Chapter 10ExceptionsExceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on: the purpose of exceptions exception messages the try-catch statement propagating exceptions the exception class hier
Wisconsin Milwaukee - CS - 141
- testing with testa.dat -Enter the radius of the wheel in inches: 18.0Enter the total time in seconds: 600.0Enter the revolutions made by the wheel: 1500.0Enter the revolutions made by the pedals: 900.0*Cadence: 90RPM: 150S
Wisconsin Milwaukee - CS - 141
16180060003000
Wisconsin Milwaukee - CS - 141
1860015009003600100005000
Wisconsin Milwaukee - CS - 141
- testing with testa.txt -Enter the radius of the wheel in inches: 18.0Enter the total time in seconds: 600.0Enter the revolutions made by the wheel: 1500.0Enter the revolutions made by the pedals: 900.0*Cadence: 90RPM: 150S
Wisconsin Milwaukee - CS - 141
Name ID Tests(first 3) Projects(Next 3) Quiz(last 4)Johnson John 93010 50 50 50 50 50 50 10 10 8 12Jackson Jack 93011 100 100 100 100 100 100 20 20 20
Wisconsin Milwaukee - CS - 141
CS 141 - Project3 Grading BreakdownCompiles/Effort/Submission 15%Execution/Correctness 15%Class/Method Use 10%Method Definitions 50%Style/Documentation 10%
Wisconsin Milwaukee - CS - 243
CS243, Spring 2009, Lecture 1, 2 and 3ATTENTION: o IN THESE NOTES BECAUSE OF LIMITED CAPABILITIES OF ASCII CHARACTERS WE USE SYMBOLS THAT ARE DIFFERENT FROM THOSE WE DEFINED IN THE CLASS. o MAKE SURE THAT YOU UNDERSTAND THE MEANING OF THOSE
Wisconsin Milwaukee - CS - 301
nj> java Klondike 876 Stock : 3CDiscard:Homecell 0:Homecell 1:Homecell 2:Homecell 3:Tableau 0: JHTableau 1: 6S 2HTableau 2: 5S 9D 3HTableau 3: 10H 6C 3D 10DTableau 4: 2S KH JD 2D 10STableau 5: 8H 7H AS KC 7C 5HTableau 6: 4H 4S KD JC
Wisconsin Milwaukee - CS - 301
PMD for Eclipse install instructions- 1. Start Eclipse. 2. Start the configuration manager : select the Help>Software Updates>Update Manager menu item. 3. In the Feature updates view find the site package (downloaded from Sourceforge) u
Wisconsin Milwaukee - CS - 412
Liberal Arts Computer Science Consortium Annual Report 1995-96 Department of Computer Science College of William and Mary
Wisconsin Milwaukee - CS - 412
<?xml version="1.0"?><!DOCTYPE Cookbook SYSTEM "recipes.dtd"><cookbook><category type="loaf"> <recipe> <name>The Basic Loaf</name> <ingredient> <qty amount="825" unit="ml"/> <item>Warm water</item> </ingredient>
Wisconsin Milwaukee - CS - 412
<?xml version = "1.0"?><ad> <year> 1960 </year> <make> Cessna </make> <model> Centurian </model> <color> Yellow with white trim </color> <location> <city> Gulfport </city> <state> MS </state> </location></ad>
Wisconsin Milwaukee - CS - 412
<?xml version = "1.0"?><events><event id="1" type="ms"><title>Forward Secure Fuzzy Extractors</title><speaker>David Goldenberg</speaker><date><year>2007</year><month>4</month><day>12</day></date><time>1400</time><place><building>McGl</bu
Wisconsin Milwaukee - CS - 652
# ex: 6.16, p. 210# void main() { # i = 1; j = 2;# if (i < 2)# j = j + 2;# else# j = 99;# k = j + 2;# / printint(k);# }func mainlabell$1=i 1=j 2if<i 2 l$2=j 99gotol$3labell$2+ t$2 j 2=j t$2l
Wisconsin Milwaukee - CS - 652
# figure 6.6, p. 177# block 0func maincall readint# block 1rec t$1= m t$1# block 2label l$2if<= t$1 0 l$7# block 3if<= t$1 5 l$5# block 4+ t$4 m 4goto l$6# block 5label l$5+ t$5 m 5= m t$5# block 6label l$6+ t$6 m 6goto l$2#
Wisconsin Milwaukee - CS - 652
# figure 3.10, p 63# with missing entry node# and c "to the left of" afunc mainif< i n l$1# node cif< i n l$7# node elabel l$5if< i n l$7# node flabel l$6if< i n l$9# node hgoto l$4# node alabel l$1call readInt# node bif< i n l$5#
Wisconsin Milwaukee - CS - 312
n = 5f = 1while n > 1: f = f * n n = n - 1
Wisconsin Milwaukee - CS - 312
x = 1y = x + a
Wisconsin Milwaukee - CS - 312
x = 1x = "abc"{<x, "abc">}
Wisconsin Milwaukee - CS - 312
x = 1x = "abc"
Wisconsin Milwaukee - CS - 312
Arithemetic + - * / div mod rem quotRelational = /= < <= > >= elem notElemBolean & |LIST FUNCTIONS-xs ! i - in C/Java: xs[i]elem x xs
Wisconsin Milwaukee - CS - 312
# Gee grammar in Wirth-style BNF, fall 2008# adapted from Clite grammar, revised, Oct. 2 2008# expression operatorsrelation = "=" | "!=" | "<" | "<=" | ">" | ">="addOperator = "+" | "-"mulOperator = "*" | "/" # expressionsexpression = a
Wisconsin Milwaukee - CS - 312
700000000402090000000008010000100060900070004030005000050600000000040702000000003
Wisconsin Milwaukee - CS - 312
import java.util.HashSet;import java.util.Iterator;/* Implements a set for a 1D 9x9 Sudoku board. Consists entirely of static methods.*/public class IndexSet extends HashSet<Integer> { / used in computing the elements of a box pri
Wisconsin Milwaukee - CSCI - 435
Apache ANT Apache Ant is a Java based glorified makefile. Apache compiles and creates .jar files automatically. All Build information for ANT is written in XML.Summary Installation Buildfiles Building Code using Apache Ant JavaDoc crea
Wisconsin Milwaukee - CSCI - 435
Internet Relay Chat - IRC - is just group chat. But instead of connecting to another person, you connect to a server and channel. Furthermore, it's much more freeform than IM group chat - you can change your name at any time, log off and on, and you
Wisconsin Milwaukee - MATH - 106
Chapter 20, Review Exercises 3,6Chapter 21, Review Exercises 1,2,3,4Chapter 23, Review Exercises 1,2,10Chapter 203.(a) N = 50,000 (b) 0 (<$50K) or 1 (>$50K) (c) False. The SD is sqrt(.2*.8) = .4. (d) True. n = 900 (e) 19% of 90
Wisconsin Milwaukee - MATH - 106
Chapter 17, Review Exercises 7,8,12Chapter 18, Review Exercises 2,6,7,12Chapter 177.(a) 321/100 = 3.21 (b) 3.78*100 = 378 (c) The key idea is to convert the statement "3 < average < 4" into thestatement "300 < sum < 400". The average
Wisconsin Milwaukee - MATH - 106
Chapter 2, Review Exercises 1,3,4,71. False. We are not provided information that would allow us to comparerates. For example, one might try to compare the proportions ofpassengers who die or the proportions of flights that crash.3. No.
Wisconsin Milwaukee - MATH - 106
Chapter 24, Review Exercises 1,3Chapter 241.(a) 81,411 inches; SE = SD/sqrt(n) = 30/5 = 6 inches (b) True. (c) False. The average of the 25 readings is 81,411. (d) False. Confidence intervals say nothing about individual readings.
Wisconsin Milwaukee - XYTHOSDOCS - 7
Sun Microsystems, Inc. Binary Code License Agreement READ THE TERMS OF THIS AGREEMENT AND ANY PROVIDED SUPPLEMENTAL LICENSE TERMS (COLLECTIVELY "AGREEMENT") CAREFULLY BEFORE OPENING THE SOFTWARE MEDIA PACKAGE. BY OPE
Wisconsin Milwaukee - XYTHOSDOCS - 7
GNU Lesser General Public LicenseVersion 2.1, February 1999Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license
Wisconsin Milwaukee - ACML - 4
ACML - Release Notes - version 4.1.0-Contents-ACML - the AMD Core Math Library - is a tuned math library designed forhigh performance on AMD64 machines, including Opteron(TM) and Athlon(TM) 64,and includes both 32-bit and 64-bit library versi
Wisconsin Milwaukee - CS - 141
Student's Name _ CS 141 - Intro. to CS - Spring 2008 - Project1 Grading Header D. NoonanExecution _ ( 30 points) Program Listing _(20 points)Correctness Stylereads first price _(2) consistent indent/align_
Wisconsin Milwaukee - CS - 141
CS 141 - Project 6 Grading Header - Spring 2008 - D. NoonanName:_Total points: _(100)Execution_( 69 points) + Source_(31 points) +Correctness_(60 points) + Style +Menu
Wisconsin Milwaukee - CS - 141
CS 141 - Project4 - Grading Header - Spring 2008 D. Noonan Name:_Correctness _(34 points) Style _(18 points)Input random seeds _(2) Consistent upper/lower case_(2)Input number o
Wisconsin Milwaukee - CS - 141
CS 141 - Project 2 Grading Header - Fall 2008 D. Noonan Name:_ TOTAL: _ (50)Correctness _(28) Style _ (22)Driver Program: Both files: Creates Room alignment/indentation_ (2) object
Wisconsin Milwaukee - CS - 141
10 111 313.53.4