Ticket Machine Project(s)

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

Today s Agenda. Quick Review

Understanding class definitions

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

UNDERSTANDING CLASS DEFINITIONS CITS1001

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

An Introduction to Processing

CSC 222: Object-Oriented Programming. Fall 2015

Recap of OO concepts. Objects, classes, methods and more. Mairead Meagher Dr. Siobhán Drohan. Produced by:

CSCI 161 Introduction to Computer Science

Java Control Statements

Object Oriented Design: Identifying Objects

CSC 222: Object-Oriented Programming. Fall 2017

Introduction to Programming Using Java (98-388)

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Java Basic Datatypees

Some miscellaneous concepts

Scope of this lecture. Repetition For loops While loops

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

COMP 250 Winter 2011 Reading: Java background January 5, 2011

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

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

Using Methods. Writing your own methods. Dr. Siobhán Drohan Mairead Meagher. Produced by: Department of Computing and Mathematics

VARIABLES AND TYPES CITS1001

Inheritance. Exploring Polymorphism. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

CSC Java Programming, Fall Java Data Types and Control Constructs

G52CPP C++ Programming Lecture 9

Methods and Data (Savitch, Chapter 5)

Principles of Object Oriented Programming. Lecture 4

PROGRAMMING FUNDAMENTALS

More Sophisticated Behaviour

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

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

Lab: PiggyBank. Defining objects & classes

CHAPTER 7 OBJECTS AND CLASSES

Chapter 4 Defining Classes I

CHAPTER 7 OBJECTS AND CLASSES

Mr. Monroe s Guide to Mastering Java Syntax

More About Objects and Methods

More About Objects and Methods. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

Inheritance. Improving Structure with Inheritance. Dr. Siobhán Drohan Mairead Meagher. Produced by:

APCS Semester #1 Final Exam Practice Problems

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Grouping Objects. Primitive Arrays and Iteration. Produced by: Dr. Siobhán Drohan. Department of Computing and Mathematics

Full file at

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

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

More Sophisticated Behaviour

TaxiBot New attributes Variables Math! TaxiBot

Chapter 6 Introduction to Defining Classes

Programming II (CS300)

Array. Prepared By - Rifat Shahriyar

Java Overview An introduction to the Java Programming Language

Values and Variables 1 / 30

Fall 2017 CISC124 9/16/2017

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.

Programming with Java

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

Objects and Classes Lecture 2

Chapter 4. Defining Classes I

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

Java Primer 1: Types, Classes and Operators

Declarations and Access Control SCJP tips

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Simple Java Reference

More About Objects and Methods. Objectives. Outline. Chapter 6

More About Objects and Methods

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CS212:Data Structure

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Java Identifiers, Data Types & Variables

Java Notes. 10th ICSE. Saravanan Ganesh

Flow Control. CSC215 Lecture

Grouping objects. Main concepts to be covered

Pace University. Fundamental Concepts of CS121 1

CS313D: ADVANCED PROGRAMMING LANGUAGE

Assignment 19 Deadline: Nov pm COSC211 CRN15376 Session 15 (Nov. 7)

EECS168 Exam 3 Review

Using Methods. Methods that handle events. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Do not start the test until instructed to do so!

Software Design and Analysis for Engineers

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

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Java Object Oriented Design. CSC207 Fall 2014

Decision Making in C

Games Course, summer Introduction to Java. Frédéric Haziza

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

CGS 3066: Spring 2015 JavaScript Reference

class objects instances Fields Constructors Methods static

Scope of this lecture

CS 251 Intermediate Programming Java Basics

5. Defining Classes and Methods

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

Programming Language Concepts: Lecture 2

1007 Imperative Programming Part II

Introduction to Programming using C++

Introduction to Java

Language Reference Manual

Language Fundamentals Summary

Transcription:

Ticket Machine Project(s) Understanding the basic contents of classes Produced by: Dr. Siobhán Drohan (based on Chapter 2, Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling) Department of Computing and Mathematics http://www.wit.ie/

Topic List Data types: primitive objects Demo of naïve ticket machine Inside classes: fields constructors methods: accessors mutators assignment statements Demo of better ticket machine Making choices: conditional statements (if)

Data Types Java uses two kinds of types: Primitive types Object types A field s data type determines the values it may contain, plus the operations that may be performed on it.

Primitive Data Types Java programming language supports eight primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. A primitive type is highlighted red when it is typed into BlueJ e.g.

Primitive Data Types (for whole numbers) Type Bytesize Minimum value (inclusive) Maximum value (inclusive) Typical Use byte short 8-bit 16-bit -128-32,768 127 32,767 Useful in applications where memory savings apply. int 32-bit -2,147,483,648 2,147,483,647 Default choice. long 64-bit - 9,223,372,036, 854,775,808 9,223,372,036,854,775,807 Used when you need a data type with a range of values larger than that provided by int.

Primitive Data Types (for decimal numbers) Type Bytesize Minimum value (inclusive) Maximum value (inclusive) float 32-bit Beyond the scope of this lecture. double 64-bit There is also a loss of precision in this data-type that we will cover in later lectures. Typical Use Useful in applications where memory savings apply. Default choice.

Primitive Data Types (others) Type Byte-size Minimum value (inclusive) char 16-bit '\u0000' (or 0) boolean 1-bit n/a Maximum value (inclusive) '\uffff' (or 65,535). Typical Use Represents a Unicode character. Holds either true or false and is typically used as a flag. http://en.wikipedia.org/wiki/list_of_unicode_characters

Default values Data Type Default Value (for fields) byte 0 short 0 int 0 long 0L float 0.0f double 0.0d char '\u0000' String (or any object) null boolean false http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Object Types All types that are not primitive are object types. Primitive fields Primitive field Object Type

Object Types Includes classes from standard java library e.g. String: private String color; Also includes user defined classes e.g. Square, Circle, etc.

Topic List Data types: primitive objects Demo of naïve ticket machine Inside classes: fields constructors methods: accessors mutators assignment statements Demo of better ticket machine Making choices: conditional statements (if)

Ticket machine an external view Exploring the behavior of a typical ticket machine (e.g. the naive-ticket-machine): 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?

Demo Exploring the behaviour of the naïve ticket machine

Ticket machines an internal view Interacting with an object gives us clues about its behavior.

Ticket machines an internal view Returns a whole number (int) representing the balance or price of the ticket. Both methods have no parameters; they don t need any information to do their task. Allows the user to insert money (an int value parameter) into the ticket machine. Doesn t return anything (it is void). Prints the ticket to the console window. Doesn t return anything (it is void).

Topic List Data types: primitive objects Demo of naïve ticket machine Inside classes: fields constructors methods: accessors mutators assignment statements Demo of better ticket machine Making choices: conditional statements (if)

Ticket machines an internal view 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 of the class omitted. The outer wrapper of TicketMachine public class ClassName //Instance Fields //Constructors //Methods The contents of a class

Instance fields public class ClassName //Instance Fields //Constructors //Methods Variables store values for an object. These variables are typically called instance fields / instance variables. public class TicketMachine private int price; private int balance; private int total; //Further details omitted. Instance fields define the state of an object i.e. the values stored in the instance fields.

Instance fields public class ClassName //Instance Fields //Constructors //Methods In BlueJ, you can view the object state by either: right clicking on the object and selecting the Inspect option OR double clicking on the object.

Instance fields public class ClassName //Instance Fields //Constructors //Methods public class TicketMachine private int price; private int balance; private int total; //Further details omitted. visibility\access modifier type variable name private int price;

Constructors public class ClassName //Instance Fields //Constructors //Methods A constructor builds an object and initialises it to a starting state. They have the same name as their class. Their access modifier is public. They store initial values in the instance fields; they often receive external parameter values for this.

Methods public class ClassName //Instance Fields //Constructors //Methods Methods implement the behaviour of objects. Java uses methods to communicate with other classes.

Method signature public class ClassName //Instance Fields //Constructors //Methods The method signature consists of a method name and its parameter type list e.g. getprice() insertmoney(int amount) The method body encloses the method s statements i.e. the code block for the method Method Body

Method return types public class ClassName //Instance Fields //Constructors //Methods Methods can return information about an object via a return value. The int before the method names mean that a whole number is returned from these methods. A method can only have one return type. The void just before the method name means that nothing is returned from these methods. void is a return type and must be included in the method signature if your method returns no information.

Return types public class ClassName //Instance Fields //Constructors //Methods In BlueJ, when you call a method that returns data, a screen will pop up with the returned data e.g. the getprice() method returns the whole number, 30.

Types of Methods public class ClassName //Instance Fields //Constructors //Methods Now that we have covered method signature and return types, we are going to look at two specific types of methods i.e. Accessor methods Mutator methods

Accessor methods public class ClassName //Instance Fields //Constructors //Methods Accessor methods return information about the state of an object. Typically they: contain a return statement (as the last executable statement in the method). define a return type.

Accessor/getter methods public class ClassName //Instance Fields //Constructors //Methods Getter methods are a specific type of accessor method. visibility modifier return type method name public int getprice() return price; start and end of method body (block) parameter list (empty) return statement

Mutator methods public class ClassName //Instance Fields //Constructors //Methods Mutator methods change (i.e. mutate!) an object s state. Typically they: contain an assignment statement take in a parameter to change the object state.

Mutator/setter methods public class ClassName //Instance Fields //Constructors //Methods Setter methods are a specific type of mutator method. visibility modifier return type method name parameter public void insertmoney(int amount) balance = balance + amount; field being mutated assignment statement

Getters/setters public class ClassName //Instance Fields //Constructors //Methods For each instance field in a class, you are normally asked to write: A getter A setter However, depending on the design of your app, you may wish to not provide getters/setters for specific fields (more on this later!)

Assignment Statement Values are stored in instance fields (and other variables) via assignment statements.

Assignment Statement Syntax Example variable = expression; price = ticketcost; A variable stores a single value, so any previous value is lost. Assignment statements work by taking the value of what appears on the right-hand side of the operator and copying that value into a variable on the lefthand side.

Topic List Data types: primitive objects Demo of naïve ticket machine Inside classes: fields constructors methods: accessors mutators assignment statements Demo of better ticket machine Making choices: conditional statements (if)

Reflecting on the naïve ticket machine The behavior is inadequate in several ways: No checks on the amounts entered. No refunds. No checks for a sensible initialisation. How can we do better? We need more sophisticated behavior.

demo Briefly explore the more sophisticated behaviour of the: better ticket machine Note: we will look at this in more detail a subsequent lecture.

Topic List Data types: primitive objects Demo of naïve ticket machine Inside classes: fields constructors methods: accessors mutators assignment statements Demo of better ticket machine Making choices: conditional statements (if)

Adding checks by making choices Naïve ticket machine Better ticket machine

Adding checks by making choices Naïve ticket machine Better ticket machine

Conditional Statement Syntax (1) 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

Conditional Statement Syntax (2) 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

Conditional Statement Syntax (3) if(condition1 perform some test) Do these statements if condition1 gave a true result else if(condition2 perform some test) Do these statements if condition1 gave a false result and condition2 gave a true result else Do these statements if both condition1 and condition2 gave a false result

Some notes on the if statement An if statement IS a statement; it is only executed once. When your if statement only has one statement inside it, you do not need to use the curly braces. For example, both of these are the same: if (balance >= price) System.out.print( Sufficient funds ); if (balance >= price) System.out.print( Sufficient funds );

Some notes on the if statement The semi-colon (;) is a statement terminator. One is circled in the code example below: if (balance >= price) System.out.print( Sufficient funds ); Your if statement does not need a statement terminator.

Improving the constructor public TicketMachine(int ticketcost) price = ticketcost; balance = 0; total = 0; Note: in the constructor set the field to a default value if invalid data was entered maybe our tickets will have a default cost of 20 if an invalid ticketcost is entered. public TicketMachine(int ticketcost) if (ticketcost > 0) else price = ticketcost; price = 20; balance = 0; total = 0;

Improving the setter / mutator public void setbalance(int amount) if (amount > 0) balance = amount; Note: The validation done at constructor level must be repeated at setter level for that field. However, in setter methods do not update the field s value if invalid data was entered (notice how the else part of the if is not there).

Study aid: can you answer these questions? Java has two kinds of types what are they? How many primitive types does Java have? Can you name them? Can you give an example of an object type? What are instance fields? What does object state mean? What is the job of a constructor? How do you recognise one i.e. method signature? What is a method signature? What is a method body?

Study aid: can you answer these questions? What are accessor methods and how would you recognise them in your source code? What are mutator methods and how would you recognise them in your source code? What are assignment statements? Can you write a statement that declares a String variable called name and updates its contents to Joe Soap? What are if statements? How do you write them? What are boolean expressions?

Questions?

Department of Computing and Mathematics http://www.wit.ie/