COS 260 DAY 3 Tony Gauvin.

Slides:



Advertisements
Similar presentations
SOFTWARE AND PROGRAMMING 1 Lecture 3: Ticketing machine: Constructor, method, menu Instructor: Prof. Boris Mirkin web-site
Advertisements

Understanding class definitions Looking inside classes 5.0.
Looking inside classes Fields, Constructors & Methods Week 3.
Fields, Constructors, Methods
Written by: Dr. JJ Shepherd
Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors.
String Concatenation (operator overloading) 3.0.
Understanding class definitions Looking inside classes 3.0.
Understanding class definitions – Part II –. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
1 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.
Understanding class definitions Looking inside classes.
5.0 Objects First with Java A Practical Introduction using BlueJ David J. Barnes Michael Kölling.
Object Oriented Design: Identifying Objects
Introduction to Java. 2 Textbook David J. Barnes & Michael Kölling Objects First with Java A Practical Introduction using BlueJ Fourth edition, Pearson.
1 COS 260 DAY 2 Tony Gauvin. 2 Agenda Questions? Class roll call Blackboard Web Resources Objects and classes 1 st Mini quiz on chap1 terms and concepts.
Classes CS 21a: Introduction to Computing I First Semester,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
SOFTWARE AND PROGRAMMING 1 In-class open-book TEST1 on 6/02 Lab SH131: Ms Mihaela Cocea (from ) Room London Knowledge Lab Emerald.
1 CSC 222: Object-Oriented Programming Spring 2013 Understanding class definitions  class structure  fields, constructors, methods  parameters  assignment.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
Understanding class definitions
1 COS 260 DAY 3 Tony Gauvin. 2 Agenda Questions? 1 st Mini quiz on chap1 terms and concepts –Today In BlackBoard –30 min., M/C and short answer, open.
Chapter 4 Introduction to Classes, Objects, Methods and strings
5.0 Objects First with Java A Practical Introduction using BlueJ David J. Barnes Michael Kölling.
1 COS 260 DAY 19 Tony Gauvin. 2 Agenda Questions? 8 th Mini Quiz not corrected yet 9 Th Mini Quiz next class –Due November 19 Finish Discussion on More.
1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.
OOP with Java, David J. Barnes/Eric Jul Defining Classes1 Object State and Complexity Objects maintain a state. State is represented by a set of attributes.
Looking inside classes Conditional Statements Week 4.
Written by: Dr. JJ Shepherd
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
OOP Basics Classes & Methods (c) IDMS/SQL News
Object-Oriented Programming in Java. 2 CS2336: Object-Oriented Programming in Java Buzzwords interfacejavadoc encapsulation coupling cohesion polymorphic.
Understanding class definitions Exploring source code 6.0.
CONDITIONALS CITS1001. Scope of this lecture if statements switch statements Source ppts: Objects First with Java - A Practical Introduction using BlueJ,
6.0 Objects First with Java A Practical Introduction using BlueJ David J. Barnes Michael Kölling.
SOFTWARE AND PROGRAMMING 1 Advert : NO TEST1 on 7/02: TEST1 will be 14/02 Lab: SH131, BBK536 6:00-7:30 (from ) [each student must have obtained.
SOFTWARE AND PROGRAMMING 1
for-each PROS CONS easy to use access to ALL items one-by-one
CSC 222: Object-Oriented Programming Fall 2015
Class definitions CITS1001 week 2.
Objects First with Java A Practical Introduction using BlueJ
Objects First with Java Creating cooperating objects
Objects First with Java Introduction to collections
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Yanal Alahmad Java Workshop Yanal Alahmad
COS 260 DAY 19 Tony Gauvin.
Understanding class definitions
Understanding class definitions
Chapter 3 Introduction to Classes, Objects Methods and Strings
COS 260 DAY 6 Tony Gauvin.
Chapter 3 Introduction to Classes, Objects Methods and Strings
COS 260 DAY 19 Tony Gauvin.
COS 260 DAY 10 Tony Gauvin.
COS 260 DAY 2 Tony Gauvin.
COS 260 DAY 18 Tony Gauvin.
CHAPTER 6 GENERAL-PURPOSE METHODS
2 The anatomy of class definitions
Objects First with Java A Practical Introduction using BlueJ
Understanding class definitions
COS 260 DAY 11 Tony Gauvin.
F II 3. Classes and Objects Objectives
COS 260 DAY 23 Tony Gauvin.
COS 260 DAY 4 Tony Gauvin.
COS 260 DAY 23 Tony Gauvin.
Objects First with Java A Practical Introduction using BlueJ
Classes CS 21a: Introduction to Computing I
COS 260 DAY 6 Tony Gauvin.
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Presentation transcript:

COS 260 DAY 3 Tony Gauvin

Agenda Questions Assignment 1 posted Miniquiz 1 Today Due September 15 Miniquiz 1 Today 30 min, open book Less than 10 questions over chapter 1 One Extra Credit Password “BabyGeeseEatAcorns” Finish Objects and Classes Begin Understanding Class Definitions

Objects and Classes Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Java Data Types Integers  int, byte, short and long Real numbers  float and double Logic  boolean Character  char Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Source code Each class has source code (Java code) associated with it that defines its details (fields and methods). Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Java Code Person person1 = new person(); person1.makevisible(); person1.moveright(); person1.moveHorizontal(50); Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Review Classes model concepts. Source code realises those concepts. Source code defines: What objects can do (methods). What data they store (attributes). Objects come into existence with pre-defined attribute values. The methods determine what objects do with their data. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Review When a method is called an object: Alters its state, and/or Uses its data to decide what to do. Some methods take parameters that affect their actions. Methods without parameters typically use their state to decide what to do. Some methods return a value. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Review Most programs contain multiple classes. At runtime, objects interact with each other to realize the overall effect of the program. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

House Project Use House Exercise 1.18 & 1.19 in class follow along – modifies where we left off with figures project © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Understanding class definitions Chap 2 Objects First with Java Understanding class definitions Chap 2 Exploring source code 6.0 © David J. Barnes and Michael Kölling

Main concepts to be covered Objects First with Java Main concepts to be covered fields constructors methods parameters assignment statements © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Objects First with Java Ticket machines Demo Source: http://www.boston.com/yourtown/news/assets_c/2012/05/fare%20increases-thumb-520x518-72121.jpg Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling © David J. Barnes and Michael Kölling

Ticket machines – an external view Objects First with Java 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? © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Objects First with Java Ticket machines Demo of naïve-ticket-machine © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Ticket machines – an internal view Objects First with Java 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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Objects First with Java Basic class structure The outer wrapper of TicketMachine public class TicketMachine { Inner part omitted. } public class ClassName { Fields Constructors Methods } The inner contents of a class © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Keywords Words with a special meaning in the language: public class private int Also known as reserved words. Always entirely lower-case. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Objects First with Java Fields 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). public class TicketMachine { private int price; private int balance; private int total;   Further details omitted. } type visibility modifier variable name private int price; © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Objects First with Java 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: Initial values stored into the fields. Parameter values often used for these. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Passing data via parameters Objects First with Java Passing data via parameters Parameters are another sort of variable. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Objects First with Java Assignment Values are stored into fields (and other variables) via assignment statements: variable = expression; balance = balance + amount; A variable can store just one value, so any previous value is lost. pattern example © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Choosing variable names 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 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Next concepts to be covered Objects First with Java Next concepts to be covered Methods: including accessor and mutator methods; String concatenation; Conditional statements; Local variables. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Objects First with Java 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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Method structure The header: The header tells us: public int getPrice() The header tells us: the visibility to objects of other classes; whether the method returns a result; the name of the method; whether the method takes parameters. The body encloses the method’s statements. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Accessor (get) methods Objects First with Java Accessor (get) methods return type visibility modifier method name parameter list (empty) public int getPrice() { return price; } return statement start and end of method body (block) © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

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. Return must be handled by the calling code NB: Returning is not printing! © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Get accessor methods public int getDiscount { retutn discount; } © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Objects First with Java Test public class CokeMachine { private price; public CokeMachine() price = 300 } public int getPrice return Price; What is wrong here? (there are five errors!) © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Objects First with Java Test public class CokeMachine { private price; public CokeMachine() price = 300 } public int getPrice return Price; int What is wrong here? ; (there are five errors!) () - } © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Objects First with Java 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. They typically contain one or more assignment statements. Often receive parameters. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Objects First with Java Mutator methods visibility modifier return type method name formal parameter public void insertMoney(int amount) { balance = balance + amount; } assignment statement field being mutated © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

set mutator methods Fields often have dedicated set mutator methods. These have a simple, distinctive form: void return type method name related to the field name single formal parameter, with the same type as the type of the field a single assignment statement © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

A typical set method public void setDiscount(int amount) { discount = amount; } We can easily infer that discount is a field of type int, i.e: private int discount; © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Protective mutators A set method does not have to always assign unconditionally to the field. The parameter may be checked for validity and rejected if inappropriate. Mutators thereby protect fields. Mutators support encapsulation. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Objects First with Java Printing from methods 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();   // Update the total collected with the balance. total = total + balance; // Clear the balance. balance = 0; } © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Objects First with Java String concatenation 4 + 5 9 "wind" + "ow" "window" "Result: " + 6 "Result: 6" "# " + price + " cents" "# 500 cents" overloading try out in codepad © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Objects First with Java Quiz System.out.println(5 + 6 + "hello"); System.out.println("hello" + 5 + 6); 11hello hello56 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Method summary 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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Reflecting on the ticket machines Objects First with Java 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 the ability to choose between different courses of action. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Making a choice in everyday life if(I have enough money left) { I will go out for a meal; } else { I will stay home and watch a movie; } © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Objects First with Java Making choices in Java ‘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 actions if condition is false ‘else’ keyword © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Making a choice in the ticket machine Objects First with Java 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); conditional statement avoids an inappropriate action © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Objects First with Java Variables – a recap 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. (life of the method) © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Scope highlighting © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Objects First with Java 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). © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

How do we write a method to ‘refund’ an excess balance? Objects First with Java How do we write a method to ‘refund’ an excess balance? write method in BlueJ; first: do it wrong © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Unsuccessful attempt public int refundBalance() { // Return the amount left. return balance; // Clear the balance. balance = 0; } It looks logical, but the language does not allow it. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Local variables 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. They are defined within a particular scope. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Objects First with Java Local variables A local variable public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund; } No visibility modifier © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Scope and lifetime The scope of a field is its whole class. The lifetime of a field is the lifetime of its containing object. 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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

In Class Exercise Goal: Write a Java Program from Scratch using BlueJ Requirements: Keep track of the score for a sports game where goals = 1 point Update game score when Home team scores Update game score when Away team scores Print score on demand Reset score to 0-0 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Objects First with Java 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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Objects First with Java Review (2) Fields, parameters and local variables are all variables. Fields persist for the lifetime of an object. Local variables are used for short-lived temporary storage. Parameters are used to receive values into a constructor or method. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

Review (3) Methods have a return type. void methods do not return anything. non-void methods always return a value. non-void methods must have a return statement. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

Objects First with Java 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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling