Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

Similar documents
11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Anatomy of a Class Encapsulation Anatomy of a Method

Chapter 4: Writing Classes

Anatomy of a Method. HW3 is due Today. September 15, Midterm 1. Quick review of last lecture. Encapsulation. Encapsulation

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

writing classes objectives chapter

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

CS1004: Intro to CS in Java, Spring 2005

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Chapter 4 Defining Classes I

Chapter 5: Writing Classes and Enums

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

class declaration Designing Classes part 2 Getting to know classes so far Review Next: 3/18/13 Driver classes:

Chapter. We've been using predefined classes. Now we will learn to write our own classes to define objects

Methods and Data (Savitch, Chapter 5)

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

CS111: PROGRAMMING LANGUAGE II

Where do objects come from? Good question!

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Objects and Classes -- Introduction

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Methods. Methods. Mysteries Revealed

Lecture 5: Methods CS2301

Handout 7. Defining Classes part 1. Instance variables and instance methods.

Designing Classes part 2

1. An operation in which an overall value is computed incrementally, often using a loop.

Chapter 6 Reflection

EECS168 Exam 3 Review

Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness.

COMP 202. Building Your Own Classes. CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) COMP 202 Objects 2 1

Assignment 1 due Monday at 11:59pm

Student Responsibilities. Mat 2170 Week 9. Notes About Using Methods. Recall: Writing Methods. Chapter Six: Objects and Classes

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

ITI Introduction to Computing II

APCS Semester #1 Final Exam Practice Problems

AP CS Unit 4: Classes and Objects Programs

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

Object Oriented Programming

Lecture #6-7 Methods

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Chapter 6 Introduction to Defining Classes

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CS 302 Week 9. Jim Williams

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Review questions. Review questions, cont d. Class Definition. Methods. Class definition: methods. April 1,

ITI Introduction to Computing II

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

Robots. Byron Weber Becker. chapter 6

CS1004: Intro to CS in Java, Spring 2005

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Table of Contents Date(s) Title/Topic Page #s. Abstraction

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS1083 Week 2: Arrays, ArrayList

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others

Object Oriented Programming

CS110D: PROGRAMMING LANGUAGE I

10. Java Classes. Classes - Technical. Example: Earthquake catalog. Classes - Conceptual

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Assertions, pre/postconditions

CSE115 Introduction to Computer Science I Coding Exercise #7 Retrospective Fall 2017

NoSuchElementException 5. Name of the Exception that occurs when you try to read past the end of the input data in a file.

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Use the scantron sheet to enter the answer to questions (pages 1-6)

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Defining Classes and Methods

COMP 202. Building Your Own Classes. CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) Instance Data. COMP Objects 2 1

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

Creating an object Instance variables

Operations. I Forgot 9/4/2016 COMPUTER SCIENCE DEPARTMENT PICNIC. If you forgot your IClicker, or your batteries fail during the exam

Introduction to Programming Using Java (98-388)

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

13. Java Classes. Educational Objectives. Classes - Technical. Definition: Classes

Programming II (CS300)

Chapter 6 Lab Classes and Objects

CS-202 Introduction to Object Oriented Programming

Lecture 2. CS118 Term planner. Refinement. Recall our first Java program. Program skeleton GCD. For your first seminar. For your second seminar

CS121: Computer Programming I

This Week s Agenda (Part A) CS121: Computer Programming I. Changing Between Loops. Things to do in-between Classes. Answer. Combining Statements

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

5. Defining Classes and Methods

An Introduction to C++

Java and OOP. Part 2 Classes and objects

Objectives. Defining Classes and Methods. Objectives. Class and Method Definitions: Outline 7/13/09

Computer Science II (20073) Week 1: Review and Inheritance

Programming II (CS300)

CSCI 161 Introduction to Computer Science

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Writing Classes Chapter 5. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Transcription:

Table of Contents Date(s) Title/Topic Page #s 11/6 Chapter 3 Reflection/Corrections 56 Chapter 4: Writing Classes 4.1 Objects Revisited 57 58-59 look over your Ch 3 Tests and write down comments/ reflections/corrections p. 56

Chapter 4: Writing Classes glue this down on p. 57 Set up p. 58 for HW and p. 59 for Cornell notes HW 4.1 Objects Revisited 58 59

Chapter 4: Writing Classes Writing Classes We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4 focuses on: > class definitions > encapsulation and Java modifiers > method declaration, invocation, and parameter passing > method overloading > method decomposition > graphics-based objects An object has: > state - descriptive characteristics > behaviors - what it can do (or what can be done to it) For example, consider a coin that can be flipped so that it's face shows either "heads" or "tails" The state of the coin is its current face (heads or tails) The behavior of the coin is that it can be flipped Note that the behavior of the coin might change its state

p. 59 4.1 Objects Revisited state descriptive characteristics of an object behaviors what an object can do or what can be done to it Classes A class is a blueprint of an object It is the model or pattern from which objects are created For example, the String class is used to define String objects Each String object contains specific characters (its state) Each String object can perform services (behaviors) such as touppercase

Classes The String class was provided for us by the Java standard class library But we can also write our own classes that define specific objects that we need For example, suppose we want to write a program that simulates the flipping of a coin We can write a Coin class to represent a coin object Classes

p. 59 4.1 Objects Revisited class blueprint of an object model or pattern from which objects are created int x, y; char ch; contains data declarations and method declarations The Coin Class In our Coin class we could define the following data: > face, an integer that represents the current face > HEADS and TAILS, integer constants that represent the two possible states We might also define the following methods: > a Coin constructor, to initialize the object > a flip method, to flip the coin > a isheads method, to determine if the current face is heads > a tostring method, to return a string description for printing

The Coin Class See CountFlips.java See Coin.java Note that the CountFlips program did not use the tostring method A program will not necessarily use every service provided by an object Once the Coin class has been defined, we can use it again in other programs as needed //******************************************************************** // CountFlips.java Author: Lewis/Loftus/Cocking // // Demonstrates the use of a programmer-defined class. //******************************************************************** public class CountFlips { //----------------------------------------------------------------- // Flips a coin multiple times and counts the number of heads // and tails that result. //----------------------------------------------------------------- public static void main (String[] args) { final int NUM_FLIPS = 1000; int heads = 0, tails = 0; Coin mycoin = new Coin(); // instantiate the Coin object for (int count=1; count <= NUM_FLIPS; count++) { mycoin.flip(); if (mycoin.isheads()) heads++; else tails++; } System.out.println ("The number flips: " + NUM_FLIPS); System.out.println ("The number of heads: " + heads); System.out.println ("The number of tails: " + tails); } }

//******************************************************************** // Coin.java Author: Lewis/Loftus/Cocking // // Represents a coin with two sides that can be flipped. //******************************************************************** public class Coin { private final int HEADS = 0; private final int TAILS = 1; private int face; //----------------------------------------------------------------- // Sets up the coin by flipping it initially. //----------------------------------------------------------------- public Coin () { flip(); } //----------------------------------------------------------------- // Flips the coin by randomly choosing a face value. //----------------------------------------------------------------- public void flip () { face = (int) (Math.random() * 2); } //----------------------------------------------------------------- // Returns true if the current face of the coin is heads. //----------------------------------------------------------------- public boolean isheads () { return (face == HEADS); } //----------------------------------------------------------------- // Returns the current face of the coin as a string. //----------------------------------------------------------------- public String tostring() { String facename; if (face == HEADS) facename = "Heads"; else facename = "Tails"; return facename; } } Data Scope The scope of data is the area in a program in which that data can be used (referenced) Data declared at the class level can be used by all methods in that class Data declared within a method can be used only in that method Data declared within a method is called local data

p. 59 4.1 Objects Revisited scope of data local data area in a program in which that data can be used (or referenced) Data declared at the class level can be used by all methods in that class Data declared within a method can be used only in that method Instance Data The face variable in the Coin class is called instance data because each instance (object) of the Coin class has its own A class declares the type of the data, but it does not reserve any memory space for it Every time a Coin object is created, a new face variable is created as well The objects of a class share the method definitions, but each has its own data space That's the only way two objects can have different states

p. 59 4.1 Objects Revisited instance data or fields instantiation a variable that must be referenced through an instance of a class must be private to protect their data the act of creating an object from a class Summary - at bottom of p. 59 What is the difference between an object and a class? HW: highlight/label object instantiation class header instance data local data method header method call

Go to Google Classroom and get the text files I shared with you: Coin CountFlips FlipRace Copy and paste these into Dr. Java and compile. Table of Contents Date(s) Title/Topic Page #s 11/10 4.2 Anatomy of a Class 60-61

Set up p. 60 for HW and p. 61 for Cornell notes HW 4.2 Anatomy of a Class 60 61 Instance Data The face variable in the Coin class is called instance data because each instance (object) of the Coin class has its own A class declares the type of the data, but it does not reserve any memory space for it Every time a Coin object is created, a new face variable is created as well The objects of a class share the method definitions, but each has its own data space That's the only way two objects can have different states

Instance Data //******************************************************************** // FlipRace.java Author: Lewis/Loftus/Cocking // // Demonstrates the existence of separate data space in multiple // instantiations of a programmer-defined class. //******************************************************************** public class FlipRace { //----------------------------------------------------------------- // Flips two coins until one of them comes up heads three times // in a row. //----------------------------------------------------------------- public static void main (String[] args) { final int GOAL = 3; int count1 = 0, count2 = 0; // Create two separate coin objects Coin coin1 = new Coin(); Coin coin2 = new Coin(); while (count1 < GOAL && count2 < GOAL) { coin1.flip(); coin2.flip(); // Print the flip results (uses Coin's tostring method) System.out.print ("Coin 1: " + coin1); System.out.println (" Coin 2: " + coin2); // Increment or reset the counters if (coin1.isheads()) count1++; else count1 = 0; if (coin2.isheads()) count2++; else count2 = 0; } // Determine the winner if (count1 < GOAL) System.out.println ("Coin 2 Wins!"); else if (count2 < GOAL) System.out.println ("Coin 1 Wins!"); else System.out.println ("It's a TIE!"); } }

Code Tracing find a partner get 2 coins from the teacher one person is coin flipper other person records output and values for count1 and count2 record work on whiteboards around the room (not at the tables) Encapsulation We can take one of two views of an object: > internal - the variables the object holds and the methods that make the object useful > external - the services that an object provides and how the object interacts From the external view, an object is an encapsulated entity, providing a set of specific services These services define the interface to the object Recall from Chapter 2 that an object is an abstraction, hiding details from the rest of the system

Encapsulation An object should be self-governing Any changes to the object's state (its variables) should be made only by that object's methods We should make it difficult, if not impossible, to access an object s variables other than via its methods The user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished Encapsulation

p. 61 4.2 Anatomy of a Class encapsulation client object methods data objects should be encapsulated the client (the code that uses the object) should not be able to reach in and change any of the variables No new notes today TOC from yesterday... 11/10 4.2 Anatomy of a Class 60-61

p. 61 4.2 Anatomy of a Class encapsulation client object methods data objects should be encapsulated the client (the code that uses the object) should not be able to reach in and change any of the variables Visibility Modifiers In Java, we accomplish encapsulation through the appropriate use of visibility modifiers A modifier is a Java reserved word that specifies particular characteristics of a method or data value We've used the modifier final to define a constant We will study two visibility modifiers: public and private

Visibility Modifiers Members of a class that are declared with public visibility can be accessed from anywhere Public variables violate encapsulation Members of a class that are declared with private visibility can only be accessed from inside the class Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package Visibility Modifiers Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clients Public methods are also called service methods A method created simply to assist a service method is called a support method Since a support method is not intended to be called by a client, it should not be declared with public visibility

Visibility Modifiers p. 61 4.2 Anatomy of a Class public variables visibility modifiers can be accessed from anywhere violate encapsulation private variables can only be accessed inside the class

p. 61 4.2 Anatomy of a Class public methods visibility modifiers service methods private methods support methods p. 61 4.2 Anatomy of a Class public private variables methods does not protect data provides services to clients protects data supports other methods in the class

Summary - at bottom of p. 61 Explain what this means: objects should be self-governing. HW: highlight/label and work on vocab object instantiation class header instance data local data method header method call Please turn in/show me the HW from Friday: HW: highlight/label object instantiation class header instance data local data method header method call

Table of Contents Date(s) Title/Topic Page #s 11/12 4.3 Anatomy of a Method 62-63 Set up p. 62 for HW and p. 63 for Cornell notes HW 4.3 Anatomy of a Method 62 63

Method Declarations A method declaration specifies the code that will be executed when the method is invoked (or called) When a method is invoked, the flow of control jumps to the method and executes its code When complete, the flow returns to the place where the method was called and continues The invocation may or may not return a value, depending on how the method is defined Method Control Flow

Method Control Flow p. 63 4.3 Anatomy of a Method method declaration calling methods specifies the code that will be executed when the method is invoked (or called) if in same class, only method name is needed if in another class, use object.method( );

Method Header p. 63 4.3 Anatomy of a Method method header method name char calc (int num1, int num2, String message) return type parameter list specifies the type and name of each parameter called the formal argument

Method Body The return Statement The return type of a method indicates the type of value that the method sends back to the calling location A method that does not return a value has a void return type A return statement specifies the value that will be returned return expression; Its expression must conform to the return type

p. 63 4.3 Anatomy of a Method method body after the method header inside the braces local data is created when the method is called and is destroyed when the method finishes executing return expression must be consistent with return type a void method doesn't return anything Parameters

Driver Programs A driver progam drives the use of other, more interesting parts of a program Driver programs are often used to test other parts of the software The Banking class contains a main method that drives the use of the Account class, exercising its services See Banking.java See Account.java p. 63 4.3 Anatomy of a Method parameters driver progam each time a method is called, the actual parameters are copied into the formal parameters drives the use of other, more interesting parts of a program often used to test other parts of the software

Summary - at bottom of p. 63 What does the return statement do? HW: highlight/label and work on vocab object instantiation class header instance data local data method header method call constant

Register for IBM Master the Mainframe Table of Contents Date(s) Title/Topic Page #s 11/13 4.4 Methods Day 2 64-65

Set up p. 64 for HW and p. 65 for Cornell notes HW 4.4 Methods Day 2 64 65 Preconditions and Postconditions A precondition is a condition that should be true when a method is called A postcondition is a condition that should be true when a method finishes executing These conditions are expressed in comments above the method header Both preconditions and postconditions are a kind of assertion, a logical statement that can be true or false which represents a programmer s assumptions about a program

p. 65 4.4 Methods Day 2 precondition a condition that should be true when the method is called postcondition a condition that should be true when the method finishes executing these conditions should be expressed in the comments above the method header! p. 65 4.4 Methods Day 2 assertion a logical statement that can be true or false and represents an assumption being made about a program includes preconditions and postconditions

Consider the following test of whether a number is odd or even: this is an assertion the program will end if the assertion is false Constructors Revisited Recall that a constructor is a special method that is used to initialize a newly created object When writing a constructor, remember that: > it has the same name as the class > it does not return a value > it has no return type, not even void > it typically sets the initial values of instance variables The programmer does not have to define a constructor for a class

p. 65 4.4 Methods Day 2 constructor is like a method that is called when an object is instantiated generally used to initialize the new object different from a regular method > name of the constructor is the name of the class > cannot return a value and doesn't have a return type p. 65 4.4 Methods Day 2 default constructor we don't have to define a constructor for every class each class has a default constructor that takes no parameters and is used if we don't provide our own

Local variables can be declared inside a method The formal parameters of a method create automatic local variables when the method is invoked When the method finishes, all local variables are destroyed (including the formal parameters) Keep in mind that instance variables, declared at the class level, exists as long as the object exists Any method in the class can refer to instance data Accessors and Mutators Since instance data usually has private visibility, it can only be accessed through methods An accessor method provides read-only access to a particular value A mutator method changes a particular value For a data value X, accessor and mutator methods are usually named getx and setx

p. 65 4.4 Methods Day 2 accessor method "getter" provides read-only access to a particular value mutator method "setter" changes a particular value Summary - at bottom of p. 65 What are constructors used for? HW: finish vocab sheet, fold in half, tape down on p. 64 Register for IBM Master the Mainframe