Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.

Slides:



Advertisements
Similar presentations
1001ICT Programming 1 Semester 1, 2011 Lecture 6 Using Java Classes (Textbook, Chapter 3, Sections 3.2 to 3.7 ONLY)
Advertisements

Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Using Classes and Objects We can create more interesting programs.
ECE122 L4: Creating Objects February 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects.
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.
Aalborg Media Lab 17-Jun-15 Software Design Lecture 4 “ Using Classes & Objects”
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.
Chapter Day 6. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 DUE Problem set 2 posted 
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
INF 523Q Chapter 2: Objects and Primitive Data (Examples)
Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 3 Using Classes and Objects 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
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.
References, Aliases, Garbage Collection and Packages Packages and Importing Classes Reading for this Lecture: L&L, Familiarize yourself with.
Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Outline Last Time: Creating Objects The GregorianCalendar Class.
***** SWTJC STEM ***** Chapter 3-1 cg 36 Java Class Libraries & API’s A class library is a set of classes that supports the development of programs. Java.
Using Classes and Objects Chapters 3 Section 3.3 Packages Section 3.4 Random Class Section 3.5 Math Class Section 3.7 Enumerated Types Instructor: Scott.
INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive.
COS 312 DAY 3 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 1 DUE right now Assignment 2 Posted – Due Feb 5 prior to class Using Classes and Objects.
Chapter 2: Objects and Primitive Data Classes and Objects String, Random, Math, NumberFormat, DecimalFormat and Wrapper Classes.
Chapter 3 Using Classes and Objects. Chapter Scope Creating objects Services of the String class The Java API class library The Random and Math classes.
Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library.
1 The String Class Every character string is an object in Java, defined by the String class Every string literal, delimited by double quotation marks,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.
Outline Creating Objects The String Class The Random and Math Classes Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Chapter 3 Using Classes and Objects 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Using Classes and Objects. We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: Object creation.
Using Classes and Objects Chapters 3 Creating Objects – Section 3.1 The String Class – Section 3.2 The Scanner Class – Section 2.6 Instructor: Scott Kristjanson.
© 2004 Pearson Addison-Wesley. All rights reserved September 7, 2007 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
CSE 1201 Object Oriented Programming Using Classes and Objects.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Using Classes and Objects (Chapter 3) Copyright © 2012 Pearson Education, Inc.
1 Chap. 3 Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L, 3.1 – 3.6.
Chapter 3 Using Classes and Objects 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Collaboration Policy Programming Tests are individual work. You may not work with others in the class.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 3: Using Classes and Objects Coming up: Creating Objects.
3-1 Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as a type to declare an object reference.
COS 312 DAY 3 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 1 posted – Due Feb 2PM Assignment 2 Posted – Due Feb 2 PM Finish Data and Expressions.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Programming in Java (COP 2250) Lecture 7 Chengyong Yang Fall, 2005.
Interactive Programs Programs that get input from the user 1 In PowerPoint, click on the speaker icon then click the "Play" button to hear the narration.
1 CMPT 126 Java Basics Using Classes and Objects.
Outline Creating Objects The String Class The Random and Math Classes Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
Using Classes and Objects We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: object creation and.
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
1 Chapter 2: Objects and Primitive Data Chapter 2 focuses on: predefined objects primitive data the declaration and use of variables expressions and operator.
1 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used as a type to declare an object reference.
© 2004 Pearson Addison-Wesley. All rights reserved January 27, 2006 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Variables in Java A variable holds either
Formatting Output & Enumerated Types & Wrapper Classes
Using Classes and Objects
CSC 1051 – Data Structures and Algorithms I
Using Classes and Objects (Chapter 3)
Classes, Libraries & Packages
title = "Java Software Solutions";
Chapter 3: Using Classes and Objects
Chapter 3 Using Classes and Objects
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.
Packages & Random and Math Classes
Outline Creating Objects The String Class The Random and Math Classes
Chapter 3 Using Classes and Objects
Presentation transcript:

Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

A Special Car Imagine you have a special remote control car called sc that can spray paint the ground and has the following behaviors: –turn(int degrees) That turns the remote control car by a specified degree Where right is positive left is negative E.g. sc.turn(90), sc.turn(-90) –startSpray() That starts spraying the ground –stopSpray() That stops spraying the ground –forward(int x) That moves the remote control car forward x distance E.g. sc.forward(100) Split into groups and draw shapes –E.g. square, rectangle, triangle, pentagon, circle

What Classes Have We Used/Created? User defined –Square –Circle –Picture –CircleApplet Java Library –String –Graphics –Color –Random –Point –Math

Outline Creating objects Using objects –Changing their state –Calling methods Class libraries / Java API

Creating Objects A field 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 variable –private String title; –private Circle sun; No object is created with this declaration An object reference variable holds the address of an object The object itself must be created separately Copyright © 2012 Pearson Education, Inc.

Creating new Objects An object is an instance of a class Creating an object is called instantiation new –Keyword in Java used to create new objects –Used before calling a constructor –EVERY constructor has the same name as its class To create a new Random object: new Random() To create a new String object: title = new String("Java Software Solutions"); To create a new Circle object: sun = new Circle(); sun = new Circle(20, 40, 80, Color.PINK);

Methods Methods are actions or behaviors associated with a class or an object Common purposes of methods are to: –Change the state of the object (mutators) E.g. setX, setY, setRadius –Get information based on the state of an object (accessors) E.g. getX, getY, getRadius, getArea, getPerimeter –Perform a general action/behavior E.g. paintComponent

Method Calls – Invoking Methods Once an object has been instantiated, we can use the dot operator to invoke its methods numChars = title.length() If a method is called on an object that is not yet created a NullPointerException will occur A method may return a value, which can be used in an assignment or expression A method invocation can be thought of as asking an object to perform a service

doIt helpMe helpMe(); obj.doIt(); someMethod External Method Call The called method is often part of another class or object Copyright © 2012 Pearson Education, Inc.

myMethod(); myMethodcompute Internal Method Call If the called method is in the same class, only the method name is needed Same as this.myMethod() Copyright © 2012 Pearson Education, Inc.

Class Libraries & the Java API A class library is a collection of classes that we can use when developing programs The Java class library = the Java API (Application Programming Interface) Examples: Copyright © 2012 Pearson Education, Inc. Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities Network communication Utilities XML document processing

The Java API Get comfortable navigating the online Java API documentation Copyright © 2012 Pearson Education, Inc.

The import Declaration When you want to use a class from a package, you import the class: import java.util.Scanner; By default, all classes of the java.lang package are imported into all Java programs It's as if all programs contain the following line: import java.lang.*; That's why we didn't have to import the System or String classes explicitly in earlier programs Copyright © 2012 Pearson Education, Inc.

The Random Class The Random class is part of the java.util package It provides methods that generate pseudorandom numbers A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values Let’s look in the Java API Copyright © 2012 Pearson Education, Inc.

Interactive Programs & Reading Input Scanner class provides methods for reading input Can be set up to read input from different sources, such as user typing values on the keyboard or reading in from a file Keyboard input represented by System.in object To read from keyboard: Scanner scan = new Scanner (System.in); Can be used with various input methods, such as: String answer = scan.nextLine(); Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // Echo.java Author: Lewis/Loftus // // Demonstrates the use of the nextLine method of the Scanner class // to read a string from the user. //******************************************************************** import java.util.Scanner; public class Echo { // // Reads a character string from the user and prints it. // public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text:"); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); }

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // Echo.java Author: Lewis/Loftus // // Demonstrates the use of the nextLine method of the Scanner class // to read a string from the user. //******************************************************************** import java.util.Scanner; public class Echo { // // Reads a character string from the user and prints it. // public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text:"); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); } Sample Run Enter a line of text: You want fries with that? You entered: "You want fries with that?" Must import to use Scanner class

Formatting Output The NumberFormat class allows you to format values as currency or percentages The DecimalFormat class allows you to format values based on any pattern Both are part of the java.text package The NumberFormat class has static methods that return a formatter object getCurrencyInstance() getPercentInstance() Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // Purchase.java Author: Lewis/Loftus // // Demonstrates the use of the NumberFormat class to format output. //******************************************************************** import java.util.Scanner; import java.text.NumberFormat; public class Purchase { // // Calculates the final price of a purchased item using values // entered by the user. // public static void main (String[] args) { final double TAX_RATE = 0.06; // 6% sales tax int quantity; double subtotal, tax, totalCost, unitPrice; Scanner scan = new Scanner (System.in); continued

Copyright © 2012 Pearson Education, Inc. continued NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); NumberFormat fmt2 = NumberFormat.getPercentInstance(); System.out.print ("Enter the quantity: "); quantity = scan.nextInt(); System.out.print ("Enter the unit price: "); unitPrice = scan.nextDouble(); subtotal = quantity * unitPrice; tax = subtotal * TAX_RATE; totalCost = subtotal + tax; // Print output with appropriate formatting System.out.println ("Subtotal: " + fmt1.format(subtotal)); System.out.println ("Tax: " + fmt1.format(tax) + " at " + fmt2.format(TAX_RATE)); System.out.println ("Total: " + fmt1.format(totalCost)); } Sample Run Enter the quantity: 5 Enter the unit price: 3.87 Subtotal: $19.35 Tax: $1.16 at 6% Total: $20.51

Formatting Output The DecimalFormat class can be used to format a floating point value in various ways For example, you can specify that the number should be truncated to three decimal places The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number See CircleStats.java Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // CircleStats.java Author: Lewis/Loftus // // Demonstrates the formatting of decimal values using the // DecimalFormat class. //******************************************************************** import java.util.Scanner; import java.text.DecimalFormat; public class CircleStats { // // Calculates the area and circumference of a circle given its // radius. // public static void main (String[] args) { int radius; double area, circumference; Scanner scan = new Scanner (System.in); continued

Copyright © 2012 Pearson Education, Inc. continued System.out.print ("Enter the circle's radius: "); radius = scan.nextInt(); area = Math.PI * Math.pow(radius, 2); circumference = 2 * Math.PI * radius; // Round the output to three decimal places DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println ("The circle's area: " + fmt.format(area)); System.out.println ("The circle's circumference: " + fmt.format(circumference)); } Sample Run Enter the circle's radius: 5 The circle's area: The circle's circumference:

The String Class Because strings are so common, we don't have to use the new operator to create a String object title = "Java Software Solutions"; This is special syntax that works only for strings Each string literal (enclosed in double quotes) represents a String object Copyright © 2012 Pearson Education, Inc.

String Methods Once a String object has been created, neither its value nor its length can be changed Therefore we say that an object of the String class is immutable However, several methods of the String class return new String objects that are modified versions of the original –E.g. substring, replace, toUpperCase, toLowerCase Copyright © 2012 Pearson Education, Inc.

String Indexes It is occasionally helpful to refer to a particular character within a string This can be done by specifying the character's numeric index The indexes begin at zero in each string In the string "Hello", the character 'H' is at index 0 and the 'o' is at index 4 Let’s look at the Java API See StringMutation.java Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // StringMutation.java Author: Lewis/Loftus // // Demonstrates the use of the String class and its methods. //******************************************************************** public class StringMutation { // // Prints a string and various mutations of it. // public static void main (String[] args) { String phrase = "Change is inevitable"; String mutation1, mutation2, mutation3, mutation4; System.out.println ("Original string: \"" + phrase + "\""); System.out.println ("Length of string: " + phrase.length()); mutation1 = phrase.concat (", except from vending machines."); mutation2 = mutation1.toUpperCase(); mutation3 = mutation2.replace ('E', 'X'); mutation4 = mutation3.substring (3, 30); continued

Copyright © 2012 Pearson Education, Inc. continued // Print each mutated string System.out.println ("Mutation #1: " + mutation1); System.out.println ("Mutation #2: " + mutation2); System.out.println ("Mutation #3: " + mutation3); System.out.println ("Mutation #4: " + mutation4); System.out.println ("Mutated length: " + mutation4.length()); } Output Original string: "Change is inevitable" Length of string: 20 Mutation #1: Change is inevitable, except from vending machines. Mutation #2: CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES. Mutation #3: CHANGX IS INXVITABLX, XXCXPT FROM VXNDING MACHINXS. Mutation #4: NGX IS INXVITABLX, XXCXPT F Mutated length: 27

Quick Check Copyright © 2012 Pearson Education, Inc. What output is produced by the following? String str = "Space, the final frontier."; System.out.println (str.length()); System.out.println (str.substring(7)); System.out.println (str.toUpperCase()); System.out.println (str.length()); 26 the final frontier. SPACE, THE FINAL FRONTIER. 26

Let’s Revisit our Lab Code And identify how we use objects: –Defining them (fields/variables) –Creating them (using constructors) –And calling methods on them to Change the object’s state (mutator) To get information from the object (accessor) Or to do something (a general action/behavior)

A Special Car (Revisited) Imagine you have a special remote control car called sc that can spray paint the ground and has the following behaviors: –turn(int degrees) That turns the remote control car by a specified degree Where right is positive left is negative E.g. sc.turn(90), sc.turn(-90) –startSpray() That starts spraying the ground –stopSpray() That stops spraying the ground –forward(int x) That moves the remote control car forward x distance E.g. sc.forward(100) Split into groups and draw shapes –E.g. square, rectangle, triangle, pentagon, circle

Homework Finish Circle Applet Lab MyProgrammingLab exercises Read Chapters 3 & 4