Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.

Slides:



Advertisements
Similar presentations
Fields, Constructors, Methods
Advertisements

1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Lecture 6 b Last time: array declaration and instantiationarray declaration and instantiation array referencearray reference bounds checkingbounds checking.
Chapter 4: Writing Classes
Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
ECE122 L4: Creating Objects February 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
Chapter Day 7. © 2007 Pearson Addison-Wesley. All rights reserved4-2 Agenda Day 7 Questions from last Class?? Problem set 1 Corrected  Good results 3.
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
ECE122 L16: Class Relationships April 3, 2007 ECE 122 Engineering Problem Solving with Java Lecture 16 Class Relationships.
Chapter 3 Using Classes and Objects. 2 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Reference … and Misc Other Topics Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
Understanding class definitions – Part II –. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
Static Class Members Wrapper Classes Autoboxing Unboxing.
Understanding class definitions Looking inside classes.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
INF 523Q Chapter 5: Enhancing Classes. 2 b We can now explore various aspects of classes and objects in more detail b Chapter 5 focuses on: object references.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley John Lewis, Peter DePasquale, and Joseph Chase Chapter 5: Writing Classes.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Writing Classes (Chapter 4)
6-1 Object-Oriented Design Today we focuses on: –the this reference (Chapter 7) –the static modifier (Chapter 7) –method overloading (Chapter 7)
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Object-Oriented Design Concepts
Java Software Solutions Lewis and Loftus Chapter 4 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects and Classes -- Introduction.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Chapter 4 Writing Classes Part 2. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Classes A class can contain data declarations and method declarations.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
Static class members.
Understanding class definitions
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
1 Enhancing Classes  Now we can explore various aspects of classes and objects in more detail  Chapter 5 focuses on: object references and aliases passing.
CSC 1051 M.A. Papalaskari, Villanova University Everyday objects: Strings and Wrappers CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari.
SEEM Java – Basic Introduction, Classes and Objects.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 3: Using Classes and Objects Coming up: Creating Objects.
Programming in Java (COP 2250) Lecture 10 Chengyong Yang Fall, 2005.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson.
© 2004 Pearson Addison-Wesley. All rights reserved January 23, 2006 Creating Objects & String Class ComS 207: Programming I (in Java) Iowa State University,
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
Object-Oriented Design Chapter 7 1. Objectives You will be able to Use the this reference in a Java program. Use the static modifier for member variables.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 5: Enhancing Classes
Variables in Java A variable holds either
Chapter 4: Writing Classes
Creating Objects & String Class
Chapter 4: Writing Classes
Understanding class definitions
More Object Oriented Programming
Understanding class definitions
Ch 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: Classes and Objects.
The this Reference The this reference allows an object to refer to itself That is, the this reference, used inside a method, refers to the object through.
Classes, Encapsulation, Methods and Constructors (Continued)
Chapter 5: Enhancing Classes
Chapter 4 Writing Classes.
Creating Objects A variable holds either a primitive value or a reference to an object A class name can be used as a type to declare an object reference.
Static is one of the modifiers that determine variable and method characteristics. The static modifier associates a variable or method with its class.
Understanding class definitions
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Object Oriented Programming Review
Packages & Random and Math Classes
Outline Creating Objects The String Class The Random and Math Classes
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Presentation transcript:

Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Agenda Variables Primitive vs. Object Types Keyword static Copyright © 2012 Pearson Education, Inc.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Variables Fields are one sort of variable –They store values through the life of an object –They are accessible throughout the class Methods can include shorter-lived variables (parameters and local variables) –They exist only as long as the method is being executed –They are only accessible from within the method

Fields / Instance Data A variable declared at the class level (such as x ) is called instance data or a field A field declares the type of the data, if it is an object type (a class) it does not create the object –We need to use new to call a constructor and assign it to that variable Objects of a class share the same method definitions, but each object has its own data space That's how two objects can have different states 10 x 25 y x 45 y

Parameters Often, we do not know the values the user will need to use in the constructor, or in any method So we use a variable in the parameter list; the name of the variable is called a formal parameter The value the user/programmer passes to the method, the value that will be stored in the formal parameter, i.e. 500, is the actual parameter

Parameters When a method is called, the actual parameters in the invocation are copied into the formal parameters in the method header public char calc(int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } ch = obj.calc(25, count, "Hello"); Copyright © 2012 Pearson Education, Inc.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Parameters Formal parameters are only available to use in the method that declares it For example, int num1 and num2 can only be used in the calc method, not in any other method In technical language, we say the scope of the parameter is restricted to the body of the constructor or method in which it is declared

Local Data As we’ve seen, 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 Copyright © 2012 Pearson Education, Inc.

To “keep” data, store it in fields Local data that will disappear So we need to store it in the fields

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

Local variables

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Scope of Variables Scope – the set of curly braces in which the variable can be used Examples: –Formal parameters & local variables The scope is the method –Fields The scope is the entire class definition

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Scope Example public class TicketMachine { public TicketMachine(int ticketCost) { price = ticketCost; balance = 0; total = 0; } // Rest of class omitted } { Scope of ticketCost

Scope Example: Undergraduate Identify scope of: –Fields –Parameters –Local variables

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Scope and life time The scope of a local variable is the block it is declared in The lifetime of a local variable is the time of execution of the block it is declared in Lifetime is dynamic & determined precisely at runtime, whereas scope is static

Variable Lifetime Lifetime of a variable = when does the variable exist? What happens if you call the a method (with a parameter) more than once? –The lifetime of a parameter is limited to a single call of the method. –If you call the method more than once, the parameter is created, then removed once the method is done. –Thus, if you have 5 methods calls, the parameter is created 5 times. What is the lifetime of a field? –Is the same as the lifetime of the object –The field is created when the object is created and destroyed when the object is removed

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Variable Recap Types of variables –Fields –Parameters –Local variables Scope & lifetime

Primitive vs. Object Types What are the difference between object and primitive types? –8 primitive data types (all start with lower case) –A library of classes, and we can make our own (all start with upper case) Are there more differences though?

38 45 Object Types & References A primitive variable contains the value itself, but an object variable contains the address of the object An object reference can be thought of as a pointer to the location of the object Rather than dealing with arbitrary addresses, we often depict a reference graphically "Steve Jobs" String name1 int num1 Copyright © 2012 Pearson Education, Inc. object type primitive type "Bill Gates" null

Assignment (Primitive types) The act of assignment takes a copy of a value and stores it in a variable For primitive types (e.g. int): num1 38 num2 96 Before: num2 = num1; num1 38 num2 38 After: Copyright © 2012 Pearson Education, Inc.

Assignment: Object/reference Types For object references, assignment copies the address (e.g. String): name2 = name1; name1 name2 Before: "Steve Jobs" "Steve Wozniak" name1 name2 After: "Steve Jobs" Copyright © 2012 Pearson Education, Inc.

Aliases Two or more references that refer to the same object are called aliases of each other That creates an interesting situation: one object can be accessed using multiple reference variables Aliases can be useful, but should be managed carefully Changing an object through one reference changes it for all of its aliases, because there is really only one object Copyright © 2012 Pearson Education, Inc.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Quiz: What is the output? int a; int b; a = 32; b = a; a = a + 1; System.out.println(b); Person a; Person b; a = new Person("Everett"); b = a; a.changeName("Delmar"); System.out.println( b.getName());

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Primitive vs. Object Types 32 ObjectType a; int a; ObjectType b; 32 int b; b = a;

Ellipse/Rectangle Examples grass 100 x 200 y fillColor red {255,0,0} 250 width 75 height sun 10 x 25 y fillColor blue {0,0,255} 60 width 75 height

Garbage Collection When an object no longer has any valid references to it, it can no longer be accessed by the program The object is useless, and therefore is called garbage Java performs automatic garbage collection periodically, returning an object's memory to the system for future use In other languages, the programmer is responsible for performing garbage collection Copyright © 2012 Pearson Education, Inc.

Static Class Members Recall that a static method is one that can be invoked through its class name For example, the methods of the Math class are static (also called class methods): result = Math.sqrt(25) Variables can be static as well Copyright © 2012 Pearson Education, Inc.

The static Modifier We declare static methods and variables using the static modifier It associates the method or variable with the class rather than with an object of that class –Static methods are sometimes called class methods –Static variables are sometimes called class variables Copyright © 2012 Pearson Education, Inc.

Static Variables Normally, each object has its own data space, but if a variable is declared as static, only one copy of the variable exists private static float price; Memory space for a static variable is created when the class is first referenced Using the final modifier you can also create static constant values (e.g. Math.PI and Color.RED) All objects instantiated from the class share its static variables Changing the value of a static variable in one object changes it for all others Copyright © 2012 Pearson Education, Inc.

Static Variable Example (Ellipse) moon x y fillColor red {255,0,0} 100 width 100 height sun 10 static x 25 static y fillColor blue {0,0,255} 60 width 60 height

Static Methods Because it is declared as static, the cube method can be invoked through the class name: value = Helper.cube(4); Copyright © 2012 Pearson Education, Inc. public class Helper { public static int cube (int num) { return num * num * num; }

Static Class Members Recall that the main method is static – it is invoked by the Java interpreter without creating an object Static methods cannot reference instance variables (fields) because instance variables don't exist until an object exists However, a static method can reference static variables or local variables Static methods and static variables often work together The following example keeps track of how many Slogan objects have been created using a static variable, and makes that information available using a static method Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // Slogan.java Author: Lewis/Loftus // // Represents a single slogan string. //******************************************************************** public class Slogan { private String phrase; private static int count = 0; // // Constructor: Sets up the slogan and counts the number of // instances created. // public Slogan (String str) { phrase = str; count++; } continue

Copyright © 2012 Pearson Education, Inc. continue // // Returns this slogan as a string. // public String toString() { return phrase; } // // Returns the number of instances of this class that have been // created. // public static int getCount () { return count; }

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // SloganCounter.java Author: Lewis/Loftus // // Demonstrates the use of the static modifier. //******************************************************************** public class SloganCounter { // // Creates several Slogan objects and prints the number of // objects that were created. // public static void main (String[] args) { Slogan obj; obj = new Slogan ("Remember the Alamo."); System.out.println (obj); obj = new Slogan ("Don't Worry. Be Happy."); System.out.println (obj); continue

Copyright © 2012 Pearson Education, Inc. continue obj = new Slogan ("Live Free or Die."); System.out.println (obj); obj = new Slogan ("Talk is Cheap."); System.out.println (obj); obj = new Slogan ("Write Once, Run Anywhere."); System.out.println (obj); System.out.println(); System.out.println ("Slogans created: " + Slogan.getCount()); }

Copyright © 2012 Pearson Education, Inc. continue obj = new Slogan ("Live Free or Die."); System.out.println (obj); obj = new Slogan ("Talk is Cheap."); System.out.println (obj); obj = new Slogan ("Write Once, Run Anywhere."); System.out.println (obj); System.out.println(); System.out.println ("Slogans created: " + Slogan.getCount()); } Output Remember the Alamo. Don't Worry. Be Happy. Live Free or Die. Talk is Cheap. Write Once, Run Anywhere. Slogans created: 5

Quick Check Copyright © 2012 Pearson Education, Inc. Why can't a static method reference an instance variable (field)? Because instance data is created only when an object is created. You don't need an object to execute a static method. And even if you had an object, which object's instance data would be referenced? (remember, the method is invoked through the class name)

Recap Variables –Types: fields, parameters, local –Scope & lifetime Primitive vs. Object Types Keyword static Copyright © 2012 Pearson Education, Inc.

Homework CodingBat Start studying for exam Understand concepts from Chapters 1-4 Copyright © 2012 Pearson Education, Inc.