Understanding class definitions Looking inside classes 5.0.

Slides:



Advertisements
Similar presentations
Variations of the Turing Machine
Advertisements

1
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
Author: Julia Richards and R. Scott Hawley
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 5: Repetition and Loop Statements Problem Solving & Program.
7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
1 RA I Sub-Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Casablanca, Morocco, 20 – 22 December 2005 Status of observing programmes in RA I.
Custom Statutory Programs Chapter 3. Customary Statutory Programs and Titles 3-2 Objectives Add Local Statutory Programs Create Customer Application For.
SOFTWARE AND PROGRAMMING 1 Lecture 3: Ticketing machine: Constructor, method, menu Instructor: Prof. Boris Mirkin web-site
1 Click here to End Presentation Software: Installation and Updates Internet Download CD release NACIS Updates.
Turing Machines.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Exercise Session 5.
PP Test Review Sections 6-1 to 6-6
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
Semantic Analysis and Symbol Tables
Looking inside classes Fields, Constructors & Methods Week 3.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
1 RA III - Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Buenos Aires, Argentina, 25 – 27 October 2006 Status of observing programmes in RA.
Basel-ICU-Journal Challenge18/20/ Basel-ICU-Journal Challenge8/20/2014.
1..
Lilian Blot PART III: ITERATIONS Core Elements Autumn 2012 TPOP 1.
CONTROL VISION Set-up. Step 1 Step 2 Step 3 Step 5 Step 4.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
1 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt Synthetic.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 9 Interactive Multimedia Authoring with Flash Introduction to Programming 1.
Types of selection structures
Essential Cell Biology
PSSA Preparation.
Essential Cell Biology
Immunobiology: The Immune System in Health & Disease Sixth Edition
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Energy Generation in Mitochondria and Chlorplasts
User Defined Functions Lesson 1 CS1313 Fall User Defined Functions 1 Outline 1.User Defined Functions 1 Outline 2.Standard Library Not Enough #1.
1 Decidability continued…. 2 Theorem: For a recursively enumerable language it is undecidable to determine whether is finite Proof: We will reduce the.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
Fields, Constructors, Methods
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.
Introduction to Java. 2 Textbook David J. Barnes & Michael Kölling Objects First with Java A Practical Introduction using BlueJ Fourth edition, Pearson.
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.
1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.
Looking inside classes Conditional Statements Week 4.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
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,
SOFTWARE AND PROGRAMMING 1
Class definitions CITS1001 week 2.
Understanding class definitions
Understanding class definitions
COS 260 DAY 3 Tony Gauvin.
2 The anatomy of class definitions
Understanding class definitions
COS 260 DAY 4 Tony Gauvin.
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Presentation transcript:

Understanding class definitions Looking inside classes 5.0

2 Main concepts to be covered fields constructors methods parameters assignment statements Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

3 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? Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

4 Ticket machines Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Demo

5 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. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

6 Basic class structure Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class TicketMachine { Inner part omitted. } public class ClassName { Fields Constructors Methods } The outer wrapper of TicketMachine The inner contents of a class

7 Keywords Words with a special meaning in the language: –public –class –private –int Also known as reserved words.

8 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). Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class TicketMachine { private int price; private int balance; private int total; Further details omitted. } private int price; visibility modifier type variable name

9 Constructors 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. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public TicketMachine(int cost) { price = cost; balance = 0; total = 0; }

10 Passing data via parameters Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Parameters are another sort of variable.

11 Assignment 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. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

12 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

13 Main concepts to be covered methods –including accessor and mutator methods conditional statements string concatenation local variables Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

14 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. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

15 Method structure The header provides the methods 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 methods statements.

16 Accessor ( get ) methods Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public int getPrice() { return price; } return type method name parameter list (empty) start and end of method body (block) return statement visibility modifier

17 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!

18 Test What is wrong here? Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class CokeMachine { private price; public CokeMachine() { price = 300 } public int getPrice { return Price; } (there are five errors!)

19 Test Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class CokeMachine { private price; public CokeMachine() { price = 300 } public int getPrice { return Price; } } ; () int - What is wrong here? (there are five errors!)

20 Mutator methods Have a similar method structure: header and body. Used to mutate (i.e., change) an objects state. Achieved through changing the value of one or more fields. –Typically contain assignment statements. –Often receive parameters. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

21 Mutator methods Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public void insertMoney(int amount) { balance = balance + amount; } return type method name parameter visibility modifier assignment statement field being mutated

22 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 parameter, with the same type as the type of the field –a single assignment statement

23 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;

24 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.

25 Printing from methods Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 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; }

26 String concatenation "wind" + "ow" "window" "Result: " + 6 "Result: 6" "# " + price + " cents" "# 500 cents" Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling overloading

27 Quiz System.out.println( "hello"); System.out.println("hello" ); Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 11hello hello56

28 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.

29 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. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

30 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.

31 Making a choice in everyday life if(I have enough money left) { go out for a meal; } else { stay home and watch a movie; }

32 Making choices in Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 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 } if keyword boolean condition to be tested actions if condition is true actions if condition is false else keyword

33 Making a choice in the ticket machine Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public void insertMoney(int amount) { if(amount > 0) { balance = balance + amount; } else { System.out.println( "Use a positive amount: " + amount); }

34 How do we write 'refundBalance'? Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

35 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. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

36 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.

37 Scope highlighting

38 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). Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

39 Local variables Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund; } A local variable No visibility modifier

40 Scope and lifetime 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.

41 Review (1) Class bodies contain fields, constructors and methods. Fields store values that determine an objects state. Constructors initialize objects – particularly their fields. Methods implement the behavior of objects. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

42 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. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

43 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.

44 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. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling