Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John."— Presentation transcript:

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

2 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

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

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

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

6 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);

7 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

8 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

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

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

11 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

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

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

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

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

16 //******************************************************************** // 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 + "\""); }

17 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

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

19 //******************************************************************** // 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

20 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

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

22 //******************************************************************** // 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

23 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: 78.54 The circle's circumference: 31.416

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

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

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

27 //******************************************************************** // 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

28 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

29 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

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

31 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

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


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

Similar presentations


Ads by Google