Agenda: Notes on Chapter 3. Create a class with constructors and methods.
|
|
- Rosa Blankenship
- 6 years ago
- Views:
Transcription
1 Bell Work 9/19/16: How would you call the default constructor for a class called BankAccount? Agenda: Notes on Chapter 3. Create a class with constructors and methods. Objectives: To become familiar with the process of implementing classes To be able to implement simple methods To understand the purpose and use of constructors
2 Chapter 3 Implementing Classes
3 Black Boxes A black box magically does its thing Hides its inner workings Encapsulation: the hiding of unimportant details What is the right concept for each particular black box? Continued
4 Black Boxes Concepts are discovered through abstraction Abstraction: taking away inessential features, until only the essence of the concept remains (details of how something works doesn t matter to the user) In object-oriented programming the black boxes from which a program is manufactured are called objects
5 Levels of Abstraction: A Real-Life Example Black boxes in a car: transmission, electronic control module, etc. Figure 1: Levels of Abstraction in Automobile Design
6 Levels of Abstraction: A Real- Life Example Users of a car do not need to understand how black boxes work Interaction of a black box with outside world is well-defined Drivers interact with car using pedals, buttons, etc. Mechanic can test that engine control module sends the right firing signals to the spark plugs For engine control module manufacturers, transistors and capacitors are black boxes produced by an electronics component manufacturer Continued
7 Levels of Abstraction: A Real- Life Example Encapsulation leads to efficiency (hiding of unimportant details): Mechanic deals only with car components (e.g. electronic control module), not with sensors and transistors Driver worries only about interaction with car (e.g. putting gas in the tank), not about motor or electronic control module
8 Levels of Abstraction: Software Design Figure 2: Levels of Abstraction in Software Design
9 Levels of Abstraction: Software Design Old times: computer programs manipulated primitive types such as numbers and characters Manipulating too many of these primitive quantities is too much for programmers and leads to errors Solution: Encapsulate routine computations to software black boxes Continued
10 Levels of Abstraction: Software Design Abstraction used to invent higher-level data types In object-oriented programming, objects are black boxes Encapsulation: Programmer using an object knows about its behavior, but not about its internal structure Continued
11 Levels of Abstraction: Software Design In software design, you can design good and bad abstractions with equal facility; understanding what makes good design is an important part of the education of a software engineer First, define behavior of a class; then, implement it
12 Self Check 1. In Chapters 1 and 2, you used System.out as a black box to cause output to appear on the screen. Who designed and implemented System.out? Ans: The programmers who designed and implemented the Java library
13 Designing the Public Interface of a Class The public constructors and methods of a class form the public interface of the class. Behavior of bank account (abstraction): deposit money withdraw money get balance
14 Designing the Public Interface of a Class: Methods Methods of BankAccount class: deposit withdraw getbalance We want to support method calls such as the following: harryschecking.deposit(2000); harryschecking.withdraw(500); System.out.println(harrysChecking.getBalance());
15 Designing the Public Interface of a Class: Method Definition access specifier (such as public) return type (such as String or void) method name (such as deposit) list of parameters (double amount for deposit) method body in { } Continued
16 Designing the Public Interface of Examples a Class: Method Definition public void deposit(double amount) {... } public void withdraw(double amount) {... } public double getbalance() {... }
17 Designing the Public Interface of a Class: Constructor Definition A constructor initializes the instance variables Constructor name is the same as the class name public BankAccount() { // body--filled in later } Continued
18 Designing the Public Interface of a Class: Constructor Definition Constructor body is executed when new object is created Statements in constructor body will set the internal data of the object that is being constructed All constructors of a class have the same name Compiler can tell constructors apart because they take different parameters
19 Purpose of a Constructor Initialize the private instance fields
20 Let s Create the Bank Account Class! It will have 2 constructors: A default constructor that takes no parameters A constructor that takes in an initial balance It will have 3 methods: Deposit method Withdraw method Get Balance method It also needs instance variables and lots of comments!
21 BankAccount Public Interface The public constructors and methods of a class form the public interface of the class. public class BankAccount { // Constructors public BankAccount() { // body--filled in later } public BankAccount(double initialbalance) { // body--filled in later } Continued
22 BankAccount Public Interface // Methods public void deposit(double amount) } { } // body--filled in later public void withdraw(double amount) { // body--filled in later } public double getbalance() { // body--filled in later } // private fields--filled in later
23 Bell Work 9/20/16: 1. How can you use the methods of the public interface of the BankAccount class to empty the harryschecking bank account? 2. Suppose you want a more powerful bank account abstraction that keeps track of an account number in addition to the balance. How would you change the public interface to accommodate this enhancement? Agenda: Finish the BankAccount class (well, preliminarily). Some more notes on Chapter 3. Objectives: To understand how to access instance fields and local variables To appreciate the importance of documentation comments
24 Commenting on the Public Interface /** Withdraws money from the bank amount the amount to withdraw */ public void withdraw(double amount) { // implementation filled in later } /** Gets the current balance of the bank the current balance */ public double getbalance() { // implementation filled in later }
25 Class Comment /** A bank account has a balance that can be changed by deposits and withdrawals. */ public class BankAccount {... } Provide documentation comments for every class every method every parameter every return value.
26 Javadoc Method Summary
27 Javadoc Method Detail
28 Self Check 5. Suppose we enhance the BankAccount class so that each account has an account number. Supply a documentation comment for the constructor BankAccount(int accountnumber, double initialbalance) Ans: /** Constructs a new bank account with a given initial accountnumber the account number for this initialbalance the initial balance for this account */
29 Self Check Continued 6. Why is the following documentation comment questionable? /** Each account has an account the account number of this account. */ int getaccountnumber() Ans: The first sentence of the method description should describe the method because it is displayed in isolation in the summary table. Better: /** Gets the account number of the bank account. */
30 Instance Fields An object stores its data in instance fields Field: a technical term for a storage location inside a block of memory Instance of a class: an object of the class The class declaration specifies the instance fields: public class BankAccount {... private double balance; }
31 Instance Fields An instance field declaration consists of the following parts: access specifier (such as private) type of variable (such as double) name of variable (such as balance) Each object of a class has its own set of instance fields You should declare all instance fields as private
32 Figure 5: Instance Fields Instance Fields
33 Accessing Instance Fields The deposit method of the BankAccount class can access the private instance field: public void deposit(double amount) { double newbalance = balance + amount; balance = newbalance; } Or public void deposit(double amount) { balance += amount; } Continued
34 Accessing Instance Fields Other methods cannot: public class BankRobber { public static void main(string[] args) { BankAccount momssavings = new BankAccount(1000);... momssavings.balance = -1000; // ERROR } } Encapsulation = Hiding data and providing access through methods
35 Self Check 7. Suppose we modify the BankAccount class so that each bank account has an account number. How does this change affect the instance fields? Ans:An instance field needs to be added to the class. What code is needed? private int accountnumber;
36 Self Check Continued 8. What are the instance fields of the Rectangle class? Ans: x value y value width height What would the code be? private int x; private int y; private int width; private int height;
37 Implementing Constructors Constructors contain instructions to initialize the instance fields of an object public BankAccount() { balance = 0; } public BankAccount(double initialbalance) { balance = initialbalance; }
38 Constructor Call Example Create a new object of type BankAccount with $1,000 BankAccount harryschecking = new BankAccount(1000); Calls the second constructor (since a construction parameter is supplied) Sets the parameter variable initialbalance to 1000 Sets the balance instance field of the newly created object to initialbalance Returns an object reference, that is, the memory location of the object, as the value of the new expression Store that object reference in the harryschecking variable
39 Implementing Methods Some methods do not return a value public void withdraw(double amount) { double newbalance = balance - amount; balance = newbalance; } Some methods return an output value public double getbalance() { return balance; }
40 Method Call Example harryschecking.deposit(500); Set the parameter variable amount to 500 Fetch the balance field of the object whose location is stored in harryschecking Add the value of amount to balance and store the result in the variable newbalance Store the value of newbalance in the balance instance field, overwriting the old value
41 Syntax 3.5: The return Statement return expression; or return; Example: return balance; Used with a void method to simply exit the method. No actual value is returned. Purpose: To specify the value that a method returns, and exit the method immediately. The return value becomes the value of the method call expression.
42 Use of the Return 01: public class BankAccount 02: { 03: public BankAccount() 04: { 05: balance = 0; 06: } 07: public void deposit(double amount) 08: { 09: if (amount == 0) 10: return; 11: else 12: balance += amount; 13: } 14: public double getbalance() 15: { 16: return balance; 17: } 18: Used to simply exit method Used to return a value - balance
43 File BankAccount.java 01: /** 02: A bank account has a balance that can be changed by 03: deposits and withdrawals. 04: */ 05: public class BankAccount 06: { 07: /** 08: Constructs a bank account with a zero balance. 09: */ 10: public BankAccount() 11: { 12: balance = 0; 13: } 14: 15: /** 16: Constructs a bank account with a given balance. initialbalance the initial balance 18: */ Continued
44 File BankAccount.java 19: public BankAccount(double initialbalance) 20: { 21: balance = initialbalance; 22: } 23: 24: /** 25: Deposits money into the bank account. amount the amount to deposit 27: */ 28: public void deposit(double amount) 29: { 30: double newbalance = balance + amount; 31: balance = newbalance; 32: } 33: 34: /** 35: Withdraws money from the bank account. amount the amount to withdraw Continued
45 File BankAccount.java 37: */ 38: public void withdraw(double amount) 39: { 40: double newbalance = balance - amount; 41: balance = newbalance; 42: } 43: 44: /** 45: Gets the current balance of the bank account. the current balance 47: */ 48: public double getbalance() 49: { 50: return balance; 51: } 52: 53: private double balance; 54: }
46 Bell Work 9/21/16: 1. The rectangle class has four instance fields: x, y, width, and height. Give a possible implementation of the getwidth method. 2. Give a possible implementation of the translate method of the Rectangle class. Agenda: Continue working on Chapter 3 programming assignments. Objectives: To understand how to access instance fields and local variables To appreciate the importance of documentation comments
47 Bell Work 9/22/16: When you run the BankAccountTester program, how many objects of class BankAccount are constructed? How many objects of type BankAccountTester? Agenda: Finish Chapter 3 notes. Continue working on Chapter 3 programming assignments. Objectives: To understand how to access instance fields and local variables To appreciate the importance of documentation comments
48 Unit Test Unit Testing is testing in isolation. This testing verifies that a class works correctly, outside a complete program. To test a class, use: 1. an environment for interactive testing (like BlueJ), or 2. write a tester class. 1. A test class is a class with a main method that contains statements to test another class. 2. It Typically carries out the following steps: Construct one or more objects of the class that is being tested Invoke one or more methods (we will test ALL methods) Print out one or more results (we will print out the results from each method we test) Print the expected values Continued
49 BankAccountTester.java 01: /** 02: A class to test the BankAccount class. 03: */ 04: public class BankAccountTester 05: { 06: /** 07: Tests the methods of the BankAccount class. args not used 09: */ 10: public static void main(string[] args) 11: { 12: BankAccount harryschecking = new BankAccount(); 13: harryschecking.deposit(2000); 14: harryschecking.withdraw(500); 15: System.out.println( Harry s Balance: + harryschecking.getbalance()); 16: System.out.println("Expected: "); 17: } 18: } Output: Harry s Balance: Expected:
50 Categories of Variables Categories of variables Instance fields (balance in BankAccount) Local variables (newbalance in deposit method) Parameter variables (amount in deposit method) An instance field belongs to an object The fields stay alive until no method uses the object any longer
51 Categories of Variables In Java, the garbage collector periodically reclaims objects when they are no longer used Local and parameter variables belong to a method Instance fields are initialized to a default value, but you must initialize local variables
52 Lifetime of Variables In main method: harryschecking.deposit(500); In deposit method: double newbalance = balance + amount; balance = newbalance; Continued
53 Lifetime of Variables Figure 7: Lifetime of Variables Continued
54 Figure 7: Lifetime of Variables Lifetime of Variables
55 Self Check 13. What do local variables and parameter variables have in common? In which essential aspect do they differ? Ans:Variables of both categories belong to methods they come alive when the method is called, and they die when the method exits. They differ in their initialization. Parameter variables are initialized with the call values; local variables must be explicitly initialized.
56 BankAccountTester.java 01: /** 02: A class to test the BankAccount class. 03: */ 04: public class BankAccountTester 05: { 06: /** 07: Tests the methods of the BankAccount class. args not used 09: */ 10: public static void main(string[] args) 11: { 12: BankAccount harryschecking = new BankAccount(); 13: harryschecking.deposit(2000); 14: harryschecking.withdraw(500); 15: System.out.println(( Harry s Balance: + harryschecking.getbalance()); 16: System.out.println("Expected: 1500"); 17: } 18: } Output: Harry s Balance: 1500 Expected: 1500 Refer to this slide in next Self-Check question. (and the BankAccount class on the board)
57 Self Check Continued 14. During execution of the BankAccountTester program in the preceding section, how many instance fields, local variables, and parameter variables were created, and what were their names? Ans: One instance field, named balance. Three local variables, one named harryschecking and two named newbalance (in the deposit and withdraw methods); two parameter variables, both named amount (in the deposit and withdraw methods).
58 Implicit and Explicit Method Parameters The implicit parameter of a method is the object on which the method is invoked harryschecking.deposit(500);
59 Implicit and Explicit Method Parameters Use of an instance field name in a method denotes the instance field of the implicit parameter public void withdraw(double amount) { double newbalance = balance - amount; balance = newbalance; }
60 Implicit and Explicit Method Parameters balance is the balance of the object to the left of the dot: momssavings.withdraw(500) means double newbalance = momssavings.balance - amount; momssavings.balance = newbalance;
61 Implicit Parameters and this Every method has one implicit parameter The implicit parameter is always called this Exception: Static methods do not have an implicit parameter (more in Chapter 8) double newbalance = balance + amount; // actually means double newbalance = this.balance + amount;
62 Implicit Parameters and this When you refer to an instance field in a method, the compiler automatically applies it to the this parameter momssavings.deposit(500);
63 Implicit Parameters and this Figure 8: The Implicit Parameter of a Method Call
64 Self Check 15. How many implicit and explicit parameters does the withdraw method of the BankAccount class have, and what are their names and types? Ans:One implicit parameter, called this, of type BankAccount, and one explicit parameter, called amount, of type double.
65 Self Check Continued 16. In the deposit method, what is the meaning of this.amount? Or, if the expression has no meaning, why not? Ans: It is not a legal expression. this is of type BankAccount and the BankAccount class has no field named amount.
66 BankAccountTester.java 01: /** 02: A class to test the BankAccount class. 03: */ 04: public class BankAccountTester 05: { 06: /** 07: Tests the methods of the BankAccount class. args not used 09: */ 10: public static void main(string[] args) 11: { 12: BankAccount harryschecking = new BankAccount(); 13: harryschecking.deposit(2000); 14: harryschecking.withdraw(500); 15: System.out.println(harrysChecking.getBalance()); 16: System.out.println("Expected: 1500"); 17: } 18: } Refer to this slide in next Self-Check question. (and the BankAccount class on the board) Output: 1500 Expected: 1500
67 Self Check Continued 17. How many implicit and explicit parameters does the main method of the BankAccountTester class have, and what are they called? Ans: No implicit parameter the method is static and one explicit parameter, called args.
68 Assignment Written Exercises Due as per your syllabus R Programming Exercises Due as per your syllabus P , 3.6, and 3.7 (Remember do 3.1 and 3.2 as one program) Programming Project 3.1 Due as per your syllabus
69 Bell Work 9/22/16: Write the 2 constructors for a class called GasPump that has variables gallons and cost per gallon. The first constructor should be the default constructor, and the second should receive two explicit parameters, gallons and cost per gallon. Agenda: Continue working on Chapter 3 programming assignments. On Monday, we will review exercises R3.1-R3.12, which you should have already done. Objectives: To understand how to access instance fields and local variables To appreciate the importance of documentation comments
70 Things to Consider For your programs in Chapter 3 You will need to construct a class file as well as a main tester file. Both should be created under the same project. Don t crowd your code use proper indentation and add comments to explain what is happening. For prog 3.1 and 3.2 do in the same prog, but show all outputs. You should not be using static methods except for the main method.
71 More items Things to Consider Create both the class and main file codes. Your output should contain expected values as well. Upload.java files to student Completed Works folder. When showing output do not change anything to make it look better. If it is not correct, you need to adjust your code. You should be able to code everything using the skills learned in chapters 1 3. If you use anything outside this, make sure you can explain it to me.
72 Things to Consider More yet Project 3 1 Remember any tester class you create must test all constructors and methods. Create two objects for the first part, create output testing each of the methods and constructors. For the second part, add to the existing code create a new object that will show at least three months worth of transactions. Your class should be able to accept any number of free transactions before applying the monthly charge. Separate your outputs to make it easier to read by including blank lines or or ===========.
73 Bell Work 9/26/16: Find all of the errors in the following code (8 errors): public class SodaMachine { private int numberofsodas; private int costpersoda; private string typeofsoda; } public SodaMachine (int nos, int cps, String tos); nos = numberofsodas; costpersode = cps; typeofsoda = tps totalcost = costpersoda * numberofsodas; } Agenda: Continue working on Chapter 3 programming assignments. Objectives: Understand how to implement classes.
74 Bell Work 9/27/16: Find all of the errors in the following code (4 errors, 1 huge): public class fixme { private int numberofitems; private String fixtype; public void gettype() { return fixtype; } public void calculate(int items); { costperitem = items / numberofitems; } } Agenda: Field Trip 10/20!!! Continue working on Chapter 3 programming assignments. Objectives: Understand how to implement classes.
75 Bell Work 9/28/16: No Bell Work Chapter 3 assignments due Tuesday. You will have today and tomorrow in class to finish them; after that you re on your own time. Review Friday Test Tuesday and Wednesday next week. Agenda: Field Trip 10/20!!! Continue working on Chapter 3 programming assignments. Objectives: Understand how to implement classes.
76 Bell Work 9/29/16: No Bell Work Chapter 3 assignments due Tuesday. You will have today in class to finish them; after that you re on your own time. Review Friday Test Tuesday and Wednesday next week. Agenda: Field Trip 10/20!!! Continue working on Chapter 3 programming assignments. Objectives: Understand how to implement classes.
77 Bell Work 9/30/16: 1) What 5 things define a method? 2) What is the public interface of a class? 3) What are the 3 types of variables and where do they belong? 4) What is garbage collection? Agenda: Field Trip 10/20!!! Chapter 3 assignments due Tuesday. Review today Test Tuesday and Wednesday next week. Objectives: Understand how to implement classes.
78 Topics for Chapter 3 Test Levels of Abstraction Black Boxes Specifying the Public Interface of a Class Commenting the Public Interface Instance Fields Implementing Constructors and Methods Unit Testing Categories of Variables Implicit and Explicit Method Parameters
Implementing Classes (P1 2006/2007)
Implementing Classes (P1 2006/2007) Fernando Brito e Abreu (fba@di.fct.unl.pt) Universidade Nova de Lisboa (http://www.unl.pt) QUASAR Research Group (http://ctp.di.fct.unl.pt/quasar) Chapter Goals To become
More informationImplementing Classes
Implementing Classes Advanced Programming ICOM 4015 Lecture 3 Reading: Java Concepts Chapter 3 Fall 2006 Slides adapted from Java Concepts companion slides 1 Chapter Goals To become familiar with the process
More information2/9/2012. Chapter Three: Implementing Classes. Chapter Goals
Chapter Three: Implementing Classes Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To understand the purpose and use of constructors To
More information9/2/2011. Chapter Goals
Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To understand the purpose and use of constructors To understand how to access instance fields
More informationICOM 4015: Advanced Programming
ICOM 4015: Advanced Programming Lecture 3 Reading: Chapter Three: Implementing Classes Copyright 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes Chapter Goals To become
More informationInheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13
Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13 Fall 2006 Adapted from Java Concepts Companion Slides 1 Chapter Goals To learn about inheritance To understand how
More informationCSEN401 Computer Programming Lab. Topics: Introduction and Motivation Recap: Objects and Classes
CSEN401 Computer Programming Lab Topics: Introduction and Motivation Recap: Objects and Classes Prof. Dr. Slim Abdennadher 16.2.2014 c S. Abdennadher 1 Course Structure Lectures Presentation of topics
More informationInheritance (P1 2006/2007)
Inheritance (P1 2006/2007) Fernando Brito e Abreu (fba@di.fct.unl.pt) Universidade Nova de Lisboa (http://www.unl.pt) QUASAR Research Group (http://ctp.di.fct.unl.pt/quasar) Chapter Goals To learn about
More informationChapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy
Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn about protected and package access control To
More informationSTUDENT LESSON A5 Designing and Using Classes
STUDENT LESSON A5 Designing and Using Classes 1 STUDENT LESSON A5 Designing and Using Classes INTRODUCTION: This lesson discusses how to design your own classes. This can be the most challenging part of
More informationCHAPTER 10 INHERITANCE
CHAPTER 10 INHERITANCE Inheritance Inheritance: extend classes by adding or redefining methods, and adding instance fields Example: Savings account = bank account with interest class SavingsAccount extends
More informationIntro to Computer Science 2. Inheritance
Intro to Computer Science 2 Inheritance Admin Questions? Quizzes Midterm Exam Announcement Inheritance Inheritance Specializing a class Inheritance Just as In science we have inheritance and specialization
More informationWeek 1 Exercises. All cs121 exercise and homework programs must in the default package and use the class names as given.
Week 1 Exercises Monday: MLK Day Unclear about building access and lab access Best case: Lab is open with TAs: 4 6 pm (Binh), 6 8 (Hoang) Worst case: locked building, lab TAs at Piazza Week 1 exercise
More informationChapter 10 Inheritance. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.
Chapter 10 Inheritance Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn about protected and package
More informationEncapsulation. Mason Vail Boise State University Computer Science
Encapsulation Mason Vail Boise State University Computer Science Pillars of Object-Oriented Programming Encapsulation Inheritance Polymorphism Abstraction (sometimes) Object Identity Data (variables) make
More informationCPS122 Lecture: Defining a Class
Objectives: CPS122 Lecture: Defining a Class last revised January 14, 2016 1. To introduce structure of a Java class 2. To introduce the different kinds of Java variables (instance, class, parameter, local)
More informationCS 170, Section /3/2009 CS170, Section 000, Fall
Lecture 18: Objects CS 170, Section 000 3 November 2009 11/3/2009 CS170, Section 000, Fall 2009 1 Lecture Plan Homework 5 : questions, comments? Managing g g Data: objects to make your life easier ArrayList:
More informationArrays and Array Lists
Arrays and Array Lists Advanced Programming ICOM 4015 Lecture 7 Reading: Java Concepts Chapter 8 Fall 2006 Slides adapted from Java Concepts companion slides 1 Lecture Goals To become familiar with using
More informationOBJECTS AND CLASSES CHAPTER. Final Draft 10/30/2011. Slides by Donald W. Smith TechNeTrain.com
CHAPTER 8 OBJECTS AND CLASSES Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/2011 Chapter Goals To understand the concepts of classes, objects and encapsulation To implement instance variables,
More informationpublic class Account { private int id; private static int nextaccountid = 0; private String name; private double balance;
public class Account { private int id; private static int nextaccountid = 0; private String name; private double balance; public double deposit(double amount) { public double withdraw(double amount) {
More informationIntroduction to Computer Science and Object-Oriented Programming
COMP 111 Introduction to Computer Science and Object-Oriented Programming Values Judgment Programs Manipulate Values Inputs them Stores them Calculates new values from existing ones Outputs them In Java
More informationChapter 8. Arrays and Array Lists. Chapter Goals. Chapter Goals. Arrays. Arrays. Arrays
Chapter 8 Arrays and Array Lists Chapter Goals To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the generalized for loop To study common array algorithms
More informationCS112 Lecture: Defining Instantiable Classes
CS112 Lecture: Defining Instantiable Classes Last revised 2/3/05 Objectives: 1. To describe the process of defining an instantiable class 2. To discuss public and private visibility modifiers. Materials:
More informationSoftware Design and Analysis for Engineers
Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:
More informationCOMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation
COMP-202 Unit 8: Defining Your Own Classes CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation Defining Our Own Classes (1) So far, we have been creating
More informationCS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class
CS112 Lecture: Defining Classes Last revised 2/3/06 Objectives: 1. To describe the process of defining an instantiable class Materials: 1. BlueJ SavingsAccount example project 2. Handout of code for SavingsAccount
More informationOutline CSE 142. Specification vs Implementation - Review. CSE142 Wi03 F-1. Instance Variables
Outline CSE 142 Class Implementation in Java Implementing classes in Java Instance variables properties Value-returning methods for queries Void methods for commands Return statement Assignment statement
More informationChapter Seven: Arrays and Array Lists. Chapter Goals
Chapter Seven: Arrays and Array Lists Chapter Goals To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the generalized for loop To study common array algorithms
More informationCreating and Using Objects
Creating and Using Objects 1 Fill in the blanks Object behaviour is described by, and object state is described by. Fill in the blanks Object behaviour is described by methods, and object state is described
More informationENGR 2710U Midterm Exam UOIT SOLUTION SHEET
SOLUTION SHEET ENGR 2710U: Object Oriented Programming & Design Midterm Exam October 19, 2012, Duration: 80 Minutes (9 Pages, 14 questions, 100 Marks) Instructor: Dr. Kamran Sartipi Name: Student Number:
More informationSample Solution Assignment 5. Question R3.1
Sample Solution Assignment 5 Question R3.1 The interface of a class is the part that the user interacts with, not necessarily knowing how it works. An implementation of is the creation of this interface.
More informationSpring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques
1 CPSC2620 Advanced Programming Spring 2003 Instructor: Dr. Shahadat Hossain 2 Today s Agenda Administrative Matters Course Information Introduction to Programming Techniques 3 Course Assessment Lectures:
More informationSoftware and Programming 1
Software and Programming 1 Lab 1: Introduction, HelloWorld Program and use of the Debugger 17 January 2019 SP1-Lab1-2018-19.pptx Tobi Brodie (tobi@dcs.bbk.ac.uk) 1 Module Information Lectures: Afternoon
More informationChapter 2 An Introduction to Objects and Classes. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.
Chapter 2 An Introduction to Objects and Classes Chapter Goals To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about parameters and return
More informationLecture 7 Objects and Classes
Lecture 7 Objects and Classes An Introduction to Data Abstraction MIT AITI June 13th, 2005 1 What do we know so far? Primitives: int, double, boolean, String* Variables: Stores values of one type. Arrays:
More informationLecture 06: Classes and Objects
Accelerating Information Technology Innovation http://aiti.mit.edu Lecture 06: Classes and Objects AITI Nigeria Summer 2012 University of Lagos. What do we know so far? Primitives: int, float, double,
More informationCSE115 Introduction to Computer Science I Coding Exercise #7 Retrospective Fall 2017
This week the main activity was a quiz activity, with a structure similar to our Friday lecture activities. The retrospective for the quiz is in Quiz-07- retrospective.pdf This retrospective explores the
More informationSoftware and Programming 1
Software and Programming 1 Lab 1: Introduction, HelloWorld Program and use of the Debugger 11 January 2018 SP1-Lab1-2017-18.pptx Tobi Brodie (tobi@dcs.bbk.ac.uk) 1 Module Information Lectures: Afternoon
More informationAssoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Dr. Marenglen Biba Laboratory Session: Exercises on classes Analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down
More informationIntroduction to Objects. James Brucker
Introduction to Objects James Brucker What is an Object? An object is a program element that encapsulates both data and behavior. An object contains both data and methods that operate on the data. Objects
More informationCSSE 220 Day 3. Check out UnitTesting and WordGames from SVN
CSSE 220 Day 3 Unit Tests and Object References Implementing Classes in Java, using Documented Stubs, Test-First Programming Check out UnitTesting and WordGames from SVN What Questions Do You Have? Syllabus
More informationCONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction
CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics COMP-202 Unit 1: Introduction Announcements Did you miss the first lecture? Come talk to me after class. If you want
More informationChapter Goals. Chapter 7 Designing Classes. Discovering Classes Actors (end in -er, -or) objects do some kinds of work for you: Discovering Classes
Chapter Goals Chapter 7 Designing Classes To learn how to discover appropriate classes for a given problem To understand the concepts of cohesion and coupling To minimize the use of side effects To document
More informationCSC Inheritance. Fall 2009
CSC 111 - Inheritance Fall 2009 Object Oriented Programming: Inheritance Within object oriented programming, Inheritance is defined as: a mechanism for extending classes by adding variables and methods
More informationContainer Vs. Definition Classes. Container Class
Overview Abstraction Defining new classes Instance variables Constructors Defining methods and passing parameters Method/constructor overloading Encapsulation Visibility modifiers Static members 14 November
More informationPractice Midterm Examination
Steve Cooper Handout #28 CS106A May 1, 2013 Practice Midterm Examination Midterm Time: Tuesday, May 7, 7:00P.M. 9:00P.M. Portions of this handout by Eric Roberts and Patrick Young This handout is intended
More informationObject-Oriented Programming
Object-Oriented Programming In C++ classes provide the functionality necessary to use object-oriented programming OOP is a particular way of organizing computer programs It doesn t allow you to do anything
More informationProgramming a Bank Database. We ll store the information in two tables: INTEGER DECIMAL(10, 2)
WE1 W o r k e d E x a m p l e 2 2.1 Programming a Bank Database In this Worked Example, we will develop a complete database program. We will reimplement the ATM simulation of Chapter 12, storing the customer
More informationPractical Session 2 Correction Don't forget to put the InputValue.java file in each project
Practical Session 2 Correction Don't forget to put the InputValue.java file in each project Exercise 1 : Bank Account 1) BankAccount class A bank account is a financial account with a banking institution
More informationFundamentos de programação
Fundamentos de programação Orientação a Objeto Classes, atributos e métodos Edson Moreno edson.moreno@pucrs.br http://www.inf.pucrs.br/~emoreno Contents Object-Oriented Programming Implementing a Simple
More informationWhat will this print?
class UselessObject{ What will this print? int evennumber; int oddnumber; public int getsum(){ int evennumber = 5; return evennumber + oddnumber; public static void main(string[] args){ UselessObject a
More informationChapter Goals. T To understand the concept of regression testing. Chapter 6 Arrays and Array Lists. Arrays Array: Sequence of values of the same type
Chapter Goals To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the generalized for loop To study common array algorithms To learn how to use two-dimensional
More informationImperative Languages!
Imperative Languages! Java is an imperative object-oriented language. What is the difference in the organisation of a program in a procedural and an objectoriented language? 30 class BankAccount { private
More informationCS 106X, Lecture 14 Classes and Pointers
CS 106X, Lecture 14 Classes and Pointers reading: Programming Abstractions in C++, Chapter 6, 11 This document is copyright (C) Stanford Computer Science and Nick Troccoli, licensed under Creative Commons
More informationCSCI 161 Introduction to Computer Science
CSCI 161 Introduction to Computer Science Department of Mathematics and Computer Science Lecture 2b A First Look at Class Design Last Time... We saw: How fields (instance variables) are declared How methods
More informationCSE 413 Winter 2001 Midterm Exam
Name ID # Score 1 2 3 4 5 6 7 8 There are 8 questions worth a total of 75 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. You may refer to
More informationEXAM Computer Science 1 Part 1
Maastricht University Faculty of Humanities and Science Department of Knowledge Engineering EXAM Computer Science 1 Part 1 Block 1.1: Computer Science 1 Code: KEN1120 Examiner: Kurt Driessens Date: Januari
More informationChapter 5: Arrays. Chapter 5. Arrays. Java Programming FROM THE BEGINNING. Copyright 2000 W. W. Norton & Company. All rights reserved.
Chapter 5 Arrays 1 5.1 Creating and Using Arrays A collection of data items stored under a single name is known as a data structure. An object is one kind of data structure, because it can store multiple
More informationMidterms Save the Dates!
University of British Columbia CPSC 111, Intro to Computation Alan J. Hu if Statements Designing Classes Abstraction and Encapsulation Readings This Week s Reading: Review Ch 1-4 (that were previously
More informationThe Scanner class reads data entered by the user. Methods: COSC Dr. Ramon Lawrence. Page 3. COSC Dr. Ramon Lawrence A) A = 6, B = 3
COSC 123 Computer Creativity Course Review Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Reading Data from the User The Scanner Class The Scanner class reads data entered
More informationUse the scantron sheet to enter the answer to questions (pages 1-6)
Use the scantron sheet to enter the answer to questions 1-100 (pages 1-6) Part I. Mark A for True, B for false. (1 point each) 1. Abstraction allow us to specify an object regardless of how the object
More informationTips from the experts: How to waste a lot of time on this assignment
Com S 227 Spring 2018 Assignment 1 80 points Due Date: Friday, February 2, 11:59 pm (midnight) Late deadline (25% penalty): Monday, February 5, 11:59 pm General information This assignment is to be done
More informationCOMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others
COMP-202 Objects, Part III Lecture Outline Static Member Variables Parameter Passing Scopes Encapsulation Overloaded Methods Foundations of Object-Orientation 2 Static Member Variables So far, member variables
More informationBasics of Java Programming. Hendrik Speleers
Hendrik Speleers Overview Building blocks of a Java program Classes Objects Primitives Methods Memory management Making a (simple) Java program Baby example Bank account system A Java program Consists
More informationCS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes
CS111: PROGRAMMING LANGUAGE II Lecture 1: Introduction to classes Lecture Contents 2 What is a class? Encapsulation Class basics: Data Methods Objects Defining and using a class In Java 3 Java is an object-oriented
More informationMidterms Save the Dates!
University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Abstraction and Encapsulation javadoc More About if Statements Readings This Week: Ch 5.1-5.4 (Ch 6.1-6.4 in 2 nd ed). (Reminder:
More informationCHAPTER 7 OBJECTS AND CLASSES
CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and
More informationAP Computer Science Unit 1. Writing Programs Using BlueJ
AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save
More informationObjects and Classes -- Introduction
Objects and Classes -- Introduction Now that some low-level programming concepts have been established, we can examine objects in more detail Chapter 4 focuses on: the concept of objects the use of classes
More informationC# Programming for Developers Course Labs Contents
C# Programming for Developers Course Labs Contents C# Programming for Developers...1 Course Labs Contents...1 Introduction to C#...3 Aims...3 Your First C# Program...3 C# The Basics...5 The Aims...5 Declaring
More informationCHAPTER 7 OBJECTS AND CLASSES
CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and
More informationClasses and Objects. COMP1400/INFS1609 Week 8. Monday, 10 September 12
Classes and Objects COMP1400/INFS1609 Week 8 Abstraction Object-oriented Programming Dividing the program into chunks at different levels of detail. Encapsulation Each chunk hides its implementation details
More informationCS112 Lecture: Working with Numbers
CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations
More informationCSIS 10A Practice Final Exam Name:
CSIS 10A Practice Final Exam Name: Multiple Choice: Each question is worth 2 points. Circle the letter of the best answer for the following questions. 1. For the following declarations: int area; String
More informationBankAccount account1 = new BankAccount(...);,this
1 6 ',, : (.new ) BankAccount account1 = new BankAccount(...); פ, פ,this,, ) \ פ\( פ פ פ 2 ) ( " פ : :? public class BankAccount {... private double balance;... 3 :),, ( 3 )queries, accessors( ), ( :)observers(
More informationTips from the experts: How to waste a lot of time on this assignment
Com S 227 Spring 2018 Assignment 1 100 points Due Date: Friday, September 14, 11:59 pm (midnight) Late deadline (25% penalty): Monday, September 17, 11:59 pm General information This assignment is to be
More informationAbout this exam review
Final Exam Review About this exam review I ve prepared an outline of the material covered in class May not be totally complete! Exam may ask about things that were covered in class but not in this review
More informationClasses. Classes as Code Libraries. Classes as Data Structures. Classes/Objects/Interfaces (Savitch, Various Chapters)
Classes Classes/Objects/Interfaces (Savitch, Various Chapters) TOPICS Classes Public versus Private Static Data Static Methods Interfaces Classes are the basis of object-oriented (OO) programming. They
More informationOutline for Today CSE 142. CSE142 Wi03 G-1. withdraw Method for BankAccount. Class Invariants
CSE 142 Outline for Today Conditional statements if Boolean expressions Comparisons (=,!=, ==) Boolean operators (and, or, not - &&,,!) Class invariants Conditional Statements & Boolean Expressions
More informationCS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.
Methods There s a method in my madness. Sect. 3.3, 8.2 1 Example Class: Car How Cars are Described Make Model Year Color Owner Location Mileage Actions that can be applied to cars Create a new car Transfer
More informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationObject-oriented basics. Object Class vs object Inheritance Overloading Interface
Object-oriented basics Object Class vs object Inheritance Overloading Interface 1 The object concept Object Encapsulation abstraction Entity with state and behaviour state -> variables behaviour -> methods
More informationContents. 8-1 Copyright (c) N. Afshartous
Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10 Introduction to Object-Oriented
More informationIntroduction to Java Unit 1. Using BlueJ to Write Programs
Introduction to Java Unit 1. Using BlueJ to Write Programs 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save
More informationStarting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,
Classes Starting Savitch Chapter 10 l l A class is a data type whose variables are objects Some pre-defined classes in C++ include int, char, ifstream Of course, you can define your own classes too A class
More informationSCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming
s SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177 Programming Time allowed: THREE hours: Answer: ALL questions Items permitted: Items supplied: There is
More informationTopic 4 Expressions and variables
Topic 4 Expressions and variables "Once a person has understood the way variables are used in programming, he has understood the quintessence of programming." -Professor Edsger W. Dijkstra Based on slides
More informationChapter 8 Designing Classes. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.
Chapter 8 Designing Classes Chapter Goals To learn how to discover appropriate classes for a given problem To understand the concepts of cohesion and coupling To minimize the use of side effects To document
More informationCPS 109 Lab 3 Alexander Ferworn Updated Fall 05. Ryerson University. School of Computer Science CPS109. Lab 3
Ryerson University Chapter 3: Using Objects School of Computer Science CPS109 Lab 3 Designing the Public Interface of a Class 1. In this lab, you will implement a vending machine. The vending machine holds
More informationUNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED
UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance
More informationNote: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.
Com S 227 Fall 2018 Miniassignment 1 40 points Due Date: Friday, October 12, 11:59 pm (midnight) Late deadline (25% penalty): Monday, October 15, 11:59 pm General information This assignment is to be done
More informationClasses. Classes as Code Libraries. Classes as Data Structures
Classes Classes/Objects/Interfaces (Savitch, Various Chapters) TOPICS Classes Public versus Private Static Data Static Methods Interfaces Classes are the basis of object-oriented (OO) programming. They
More informationUNDERSTANDING CLASS DEFINITIONS CITS1001
UNDERSTANDING CLASS DEFINITIONS CITS1001 Main concepts to be covered Fields / Attributes Constructors Methods Parameters Source ppts: Objects First with Java - A Practical Introduction using BlueJ, David
More informationAP Computer Science Unit 1. Writing Programs Using BlueJ
AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save
More informationAdministration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7
Administration Classes CS 99 Summer 2000 Michael Clarkson Lecture 7 Lab 7 due tomorrow Question: Lab 6.equals( SquareRoot )? Lab 8 posted today Prelim 2 in six days! Covers two weeks of material: lectures
More informationCSE 113 A. Announcements - Lab
CSE 113 A February 21-25, 2011 Announcements - Lab Lab 1, 2, 3, 4; Practice Assignment 1, 2, 3, 4 grades are available in Web-CAT look under Results -> Past Results and if looking for Lab 1, make sure
More informationcoe318 Lab 1 Introduction to Netbeans and Java
coe318 Lab 1 Week of September 12, 2016 Objectives Lean how to use the Netbeans Integrated Development Environment (IDE). Learn how to generate and write formatted API documentation. Add a constructor,
More informationReview. these are the instance variables. these are parameters to the methods
Review Design a class to simulate a bank account Implement the class Write a demo program that creates bank accounts Write junit tests for the bank account class Review What data items are associated with
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationCS 1302 Chapter 9 (Review) Object & Classes
CS 1302 Chapter 9 (Review) Object & Classes Reference Sections 9.2-9.5, 9.7-9.14 9.2 Defining Classes for Objects 1. A class is a blueprint (or template) for creating objects. A class defines the state
More information