public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods

Similar documents
Today s Agenda. Quick Review

Understanding class definitions. Looking inside classes (based on lecture slides by Barnes and Kölling)

UNDERSTANDING CLASS DEFINITIONS CITS1001

Understanding class definitions

Ticket Machine Project(s)

Defining Classes. Chap 1 introduced many concepts informally, in this chapter we will be more formal in defining

CSCI 161 Introduction to Computer Science

CSC 222: Object-Oriented Programming. Fall 2015

CSC 222: Object-Oriented Programming. Fall 2017

Chapter 4 Defining Classes I

If too much money is inserted the machine takes it all - no refund. If there isn't enough money inserted, it still prints out the ticket.

Introduction to Programming Using Java (98-388)

Chapter 6 Introduction to Defining Classes

CS 302: Introduction to Programming in Java. Lecture 15

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

EECS168 Exam 3 Review

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

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

G52CPP C++ Programming Lecture 9

Fundamental Concepts and Definitions

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

Object Oriented Programming in C#

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

Anatomy of a Class Encapsulation Anatomy of a Method

Java and OOP. Part 2 Classes and objects

Defining Classes and Methods

Chapter 4: Writing Classes

And Even More and More C++ Fundamentals of Computer Science

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

MID-SEMESTER TEST 2014

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

Principles of Object Oriented Programming. Lecture 4

CS 231 Data Structures and Algorithms, Fall 2016

Robots. Byron Weber Becker. chapter 6

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

class objects instances Fields Constructors Methods static

Encapsulation. Mason Vail Boise State University Computer Science

Chapter 7 User-Defined Methods. Chapter Objectives

Defensive Programming

Do not start the test until instructed to do so!

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

About this exam review

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

Java Primer 1: Types, Classes and Operators

Short Notes of CS201

CS112 Lecture: Working with Numbers

Math Modeling in Java: An S-I Compartment Model

CS201 - Introduction to Programming Glossary By

Declarations and Access Control SCJP tips

QUIZ Friends class Y;

Frequently Asked Questions

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Objects and Classes Lecture 2

Objects as a programming concept

TaxiBot New attributes Variables Math! TaxiBot

CSCI 1301: Introduction to Computing and Programming Spring 2019 Lab 10 Classes and Methods

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

Objects and State. COMP1400 Week 9. Wednesday, 19 September 12

MIDTERM REVIEW. midterminformation.htm

// constructor: takes a String as parameter and creates a public Cat (String x) { name = x; age = 0; lives = 9; // cats start out with 9 lives }

CSCI 1301: Introduction to Computing and Programming Summer 2018 Lab 07 Classes and Methods

9 Working with the Java Class Library

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

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

Packages Inner Classes

For this section, we will implement a class with only non-static features, that represents a rectangle

Builder pattern. A creational pattern

Objects and Iterators

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

In Java there are three types of data values:

ECE 122. Engineering Problem Solving with Java

Array. Prepared By - Rifat Shahriyar

CPS122 Lecture: Defining a Class

CS 106 Introduction to Computer Science I

CS113: Lecture 4. Topics: Functions. Function Activation Records

Java Identifiers, Data Types & Variables

Chapter 4. Defining Classes I

CS1083 Week 2: Arrays, ArrayList

BM214E Object Oriented Programming Lecture 8

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Procedures, Parameters, Values and Variables. Steven R. Bagley

CS112 Lecture: Defining Instantiable Classes

CS 302 Week 9. Jim Williams

CHAPTER 7 OBJECTS AND CLASSES

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Programming Language Concepts: Lecture 2

Lecture 3. Lecture

Chief Reader Report on Student Responses:

Methods and Data (Savitch, Chapter 5)

Example: Monte Carlo Simulation 1

c) And last but not least, there are javadoc comments. See Weiss.

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

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

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

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

Transcription:

Main concepts to be covered Understanding class definitions Looking inside classes fields constructors methods parameters assignment statements 5.0 2 Ticket machines an external view Exploring the behavior of a typical ticket machine. Use the naive-ticket-machine project. Machines supply tickets of a fixed price. How is that price determined? How is money entered into a machine? How does a machine keep track of the money that is entered? Ticket machines Demo 3 4 Ticket machines an internal view Interacting with an object gives us clues about its behavior. Looking inside allows us to determine how that behavior is provided or implemented. All Java classes have a similar-looking internal view. Basic class structure public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods The outer wrapper of TicketMachine The inner contents of a class 5 6

Keywords Words with a special meaning in the language: public class private int Also known as reserved words. Fields store values for an object. They are also known as instance variables. Fields define the state of an object. Use Inspect to view the state. Some values change often. Some change rarely (or not at all). Fields public class TicketMachine private int price; private int balance; private int total; Further details omitted. visibility modifier type variable name private int price; 7 8 Constructors public TicketMachine(int cost) price = cost; balance = 0; total = 0; Initialize an object. Have the same name as their class. Close association with the fields. Store initial values into the fields. External parameter values for this. Passing data via parameters Parameters are another sort of variable. 9 10 Assignment Choosing variable names Values are stored into fields (and other variables) via assignment statements: variable = expression; price = cost; A variable stores a single value, so any previous value is lost. There is a lot of freedom over choice of names. Use it wisely! Choose expressive names to make code easier to understand: price, amount, name, age, etc. Avoid single-letter or cryptic names: w, t5, xyz123 11 12

Main concepts to be covered methods including accessor and mutator methods conditional statements string concatenation local variables Methods Methods implement the behavior of objects. Methods have a consistent structure comprised of a header and a body. Accessor methods provide information about an object. Mutator methods alter the state of an object. Other sorts of methods accomplish a variety of tasks. 13 14 Method structure Accessor (get) methods The header provides the method s signature: public int getprice() The header tells us: the name of the method what parameters it takes whether it returns a result its visibility to objects of other classes The body encloses the method s statements. visibility modifier return type public int getprice() return price; method name start and end of method body (block) parameter list (empty) return statement 15 16 Accessor methods An accessor method always has a return type that is not void. An accessor method returns a value (result) of the type given in the header. The method will contain a return statement to return the value. NB: Returning is not printing! Test public class CokeMachine private price; public CokeMachine() price = 300 public int getprice return Price; What is wrong here? (there are five errors!) 17 18

Test public class CokeMachine int private price; public CokeMachine() price = 300; public int getprice() return -Price; What is wrong here? (there are five errors!) Mutator methods Have a similar method structure: header and body. Used to mutate (i.e., change) an object s state. Achieved through changing the value of one or more fields. Typically contain assignment statements. Often receive parameters. 19 20 Mutator methods set mutator methods visibility modifier return type method name public void insertmoney(int amount) balance = balance + amount; field being mutated parameter assignment statement Fields often have dedicated set mutator methods. These have a simple, distinctive form: void return type method name related to the field name single parameter, with the same type as the type of the field a single assignment statement 21 22 A typical set method public void setdiscount(int amount) discount = amount; We can infer that discount is a field of type int, i.e: private int discount; Protective mutators A set method does not have to assign the parameter to the field. The parameter may be checked for validity and rejected if inappropriate. Mutators thereby protect fields. Mutators support encapsulation. 23 24

Printing from methods String concatenation public void printticket() // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# The BlueJ Line"); System.out.println("# Ticket"); System.out.println("# " + price + " cents."); System.out.println("##################"); System.out.println(); // Update the total collected with the balance. total = total + balance; // Clear the balance. balance = 0; 4 + 5 9 "wind" + "ow" "window" "Result: " + 6 "Result: 6" "# " + price + " cents" "# 500 cents" overloading 25 26 Quiz Method summary System.out.println(5 + 6 + "hello"); 11hello System.out.println("hello" + 5 + 6); hello56 Methods implement all object behavior. A method has a name and a return type. The return-type may be void. A non-void return type means the method will return a value to its caller. A method might take parameters. Parameters bring values in from outside for the method to use. 27 28 Reflecting on the ticket machines Their behavior is inadequate in several ways: No checks on the amounts entered. No refunds. No checks for a sensible initialization. How can we do better? We need more sophisticated behavior. Making choices in everyday life If I have enough money left, then I will go out for a meal otherwise I will stay home and watch a movie. 29 30

Making a choice in everyday life Making choices in Java if(i have enough money left) go out for a meal; else stay home and watch a movie; if keyword boolean condition to be tested actions if condition is true if(perform some test) Do these statements if the test gave a true result else Do these statements if the test gave a false result else keyword actions if condition is false 31 32 Making a choice in the ticket machine public void insertmoney(int amount) if(amount > 0) balance = balance + amount; else System.out.println( "Use a positive amount: " + amount); How do we write 'refundbalance'? 33 34 Variables a recap Local variables Fields are one sort of variable. They store values through the life of an object. They are accessible throughout the class. Parameters are another sort of variable: They receive values from outside the method. They help a method complete its task. Each call to the method receives a fresh set of values. Parameter values are short lived. Methods can define their own, local variables: Short lived, like parameters. The method sets their values unlike parameters, they do not receive external values. Used for temporary calculation and storage. They exist only as long as the method is being executed. They are only accessible from within the method. 35 36

Scope highlighting Scope and lifetime Each block defines a new scope. Class, method and statement. Scopes may be nested: statement block inside another block inside a method body inside a class body. Scope is static (textual). Lifetime is dynamic (runtime). 37 38 Local variables Scope and lifetime No visibility modifier public int refundbalance() int amounttorefund; amounttorefund = balance; balance = 0; return amounttorefund; A local variable The scope of a local variable is the block in which it is declared. The lifetime of a local variable is the time of execution of the block in which it is declared. The scope of a field is its whole class. The lifetime of a field is the lifetime of its containing object. 39 40 Review (1) Class bodies contain fields, constructors and methods. Fields store values that determine an object s state. Constructors initialize objects particularly their fields. Methods implement the behavior of objects. Review (2) Fields, parameters and local variables are all variables. Fields persist for the lifetime of an object. Parameters are used to receive values into a constructor or method. Local variables are used for short-lived temporary storage. 41 42

Review (3) Methods have a return type. void methods do not return anything. non-void methods return a value. non-void methods have a return statement. Review (4) Correct behavior often requires objects to make decisions. Objects can make decisions via conditional (if) statements. A true-or-false test allows one of two alternative courses of actions to be taken. 43 44