Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Chapter 10 Thinking in Objects 1.

Similar presentations


Presentation on theme: "Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Chapter 10 Thinking in Objects 1."— Presentation transcript:

1 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Chapter 10 Thinking in Objects 1

2 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Motivations You see the advantages of object-oriented programming from the preceding chapter. This chapter will demonstrate how to solve problems using the object-oriented paradigm. 2

3 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Objectives  To apply class abstraction to develop software (§10.2).  To explore the differences between the procedural paradigm and object- oriented paradigm (§10.3).  To discover the relationships between classes (§10.4).  To design programs using the object-oriented paradigm (§§10.5–10.6).  To create objects for primitive values using the wrapper classes (Byte, Short, Integer, Long, Float, Double, Character, and Boolean) (§10.7).  To simplify programming using automatic conversion between primitive types and wrapper class types (§10.8).  To use the BigInteger and BigDecimal classes for computing very large numbers with arbitrary precisions (§10.9).  To use the String class to process immutable strings (§10.10).  To use the StringBuilder and StringBuffer classes to process mutable strings (§10.11). 3

4 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 4 major principles of Object-Oriented Programming (OOP) 1.Encapsulation is the hiding of data implementation by restricting access to Accessors is a method that is used to ask an object about itself, like a get method) and mutators are public methods that are used to modify the state of an object, while hiding of exactly how the data gets modified.) 2.Abstraction is used to manage complexity. Software developers use abstraction to decompose complex systems into smaller components. 3.Inheritance, objects can relate to each other with either a “has a”, “uses a” or an “is a” relationship. “Is a” is the inheritance way of object relationship. 4.Polymorphism means one name, many forms. Polymorphism manifests itself by having multiple methods all with the same name, but slightly different functionality. 4

5 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Class Abstraction and Encapsulation Class abstraction means to separate class implementation from the use of the class. The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user. 5

6 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. UML 6 UML is a standard notation for the modeling of real- world objects as a first step in developing an object- oriented design methodology. Its notation is derived from and unifies the notations of three object- oriented design (OOD) and analysis methodologies.

7 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Designing the Loan Class 7 TestLoanClass Run Loan

8 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Object-Oriented Thinking Chapters 1-8 introduced fundamental programming techniques for problem solving using loops, methods, and arrays. The studies of these techniques lay a solid foundation for object-oriented programming. Classes provide more flexibility and modularity for building reusable software. This section improves the solution for a problem introduced in Chapter 3 using the object-oriented approach. From the improvements, you will gain the insight on the differences between the procedural programming and object-oriented programming and see the benefits of developing reusable code using objects and classes. 8

9 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. The BMI Class 9 UseBMIClass Run BMI

10 10 public class UseBMIClass { public static void main(String[] args) { BMI bmi1 = new BMI("John Doe", 18, 145, 70); System.out.println("The BMI for " + bmi1.getName() + " is " + bmi1.getBMI() + " " + bmi1.getStatus()); BMI bmi2 = new BMI("Peter King", 215, 70); System.out.println("The BMI for " + bmi2.getName() + " is " + bmi2.getBMI() + " " + bmi2.getStatus()); } } public class BMI { private String name; private int age; private double weight; // in pounds private double height; // in inches public static final double KILOGRAMS_PER_POUND = 0.45359237; public static final double METERS_PER_INCH = 0.0254; public BMI(String name, int age, double weight, double height) { this.name = name; this.age = age; this.weight = weight; this.height = height; } public BMI(String name, double weight, double height) { this(name, 20, weight, height); } public double getBMI() { double bmi = weight * KILOGRAMS_PER_POUND / ((height * METERS_PER_INCH) * (height * METERS_PER_INCH)); return Math.round(bmi * 100) / 100.0; } public String getStatus() { double bmi = getBMI(); if (bmi < 16) return "seriously underweight"; else if (bmi < 18) return "underweight"; else if (bmi < 24) return "normal weight"; else if (bmi < 29) return "over weight"; else if (bmi < 35) return "seriously over weight"; else return "gravely over weight"; } public String getName() { return name; } public int getAge() { return age; } public double getWeight() { return weight; } public double getHeight() { return height; } }

11 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Object Composition Composition is actually a special case of the aggregation relationship. Aggregation models has-a relationships and represents an ownership relationship between two objects. The owner object is called an aggregating object and its class an aggregating class. The subject object is called an aggregated object and its class an aggregated class. 11

12 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Class Representation An aggregation relationship is usually represented as a data field in the aggregating class. For example, the relationship in Figure 10.6 can be represented as follows: 12

13 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Aggregation or Composition Since aggregation and composition relationships are represented using classes in similar ways, many texts don’t differentiate them and call both compositions. 13

14 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Aggregation Between Same Class Aggregation may exist between objects of the same class. For example, a person may have a supervisor. 14 public class Person { // The type for the data is the class itself private Person supervisor;... }

15 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Aggregation Between Same Class What happens if a person has several supervisors? 15

16 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. class Address { int streetNum; String city; String state; String country; Address(int street, String c, String st, String coun) { this.streetNum=street; this.city =c; this.state = st; this.country = coun; } } class StudentClass { int rollNum; String studentName; Address studentAddr; StudentClass(int roll, String name, Address addr){ this.rollNum=roll; this.studentName=name; this.studentAddr = addr; } public static void main(String args[]){ Address ad = new Address(55, "Agra", "UP", "India"); StudentClass obj = new StudentClass(123, “Sarah", ad); System.out.println(obj.rollNum); System.out.println(obj.studentName); System.out.println(obj.studentAddr.streetNum); System.out.println(obj.studentAddr.city); System.out.println(obj.studentAddr.state); System.out.println(obj.studentAddr.country); } } 16 This example shows the Aggregation between Student and Address classes. You can see that in Student class I have used Address class to obtain student address. Its a typical example of Aggregation in Java. The reason we use Aggregation because of re-usability. Like: College address and Student’s address

17 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Example: The Course Class 17 TestCourse Run Course

18 18 public class TestCourse { public static void main(String[] args) { Course course1 = new Course("Data Structures"); Course course2 = new Course("Database Systems"); course1.addStudent("Peter Jones"); course1.addStudent("Brian Smith"); course1.addStudent("Anne Kennedy"); course2.addStudent("Peter Jones"); course2.addStudent("Steve Smith"); System.out.println("Number of students in course1: " + course1.getNumberOfStudents()); String[] students = course1.getStudents(); for (int i = 0; i < course1.getNumberOfStudents(); i++) System.out.print(students[i] + ", "); System.out.println(); System.out.print("Number of students in course2: " + course2.getNumberOfStudents()); } } public class Course { private String courseName; private String[] students = new String[100]; private int numberOfStudents; public Course(String courseName) { this.courseName = courseName; } public void addStudent(String student) { students[numberOfStudents] = student; numberOfStudents++; } public String[] getStudents() { return students; } public int getNumberOfStudents() { return numberOfStudents; } public String getCourseName() { return courseName; } public void dropStudent(String student) { // Left as an exercise in Exercise 9.9 } }

19 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Example: The StackOfIntegers Class 19 Run TestStackOfIntegers

20 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Designing the StackOfIntegers Class 20

21 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Implementing StackOfIntegers Class 21 StackOfIntegers

22 22 public class TestStackOfIntegers { public static void main(String[] args) { StackOfIntegers stack = new StackOfIntegers(); for (int i = 0; i < 10; i++) stack.push(i); while (!stack.empty()) System.out.print(stack.pop() + " "); } } public class StackOfIntegers { private int[] elements; private int size; public static final int DEFAULT_CAPACITY = 16; /** Construct a stack with the default capacity 16 */ public StackOfIntegers() { this(DEFAULT_CAPACITY); } /** Construct a stack with the specified maximum capacity */ public StackOfIntegers(int capacity) { elements = new int[capacity]; } /** Push a new integer into the top of the stack */ public void push(int value) { if (size >= elements.length) { int[] temp = new int[elements.length * 2]; System.arraycopy(elements, 0, temp, 0, elements.length); elements = temp; } elements[size++] = value; } /** Return and remove the top element from the stack */ public int pop() { return elements[--size]; } /** Return the top element from the stack */ public int peek() { return elements[size - 1]; } /** Test whether the stack is empty */ public boolean empty() { return size == 0; } /** Return the number of elements in the stack */ public int getSize() { return size; } }

23 23 Wrapper Classes  Boolean  Character  Short  Byte 23  Integer  Long  Float  Double NOTE: (1) The wrapper classes do not have no-arg constructors. (2) The instances of all wrapper classes are immutable, i.e., their internal values cannot be changed once the objects are created.

24 24 The Integer and Double Classes 24

25 25 Numeric Wrapper Class Constants Each numerical wrapper class has the constants MAX_VALUE and MIN_VALUE. MAX_VALUE represents the maximum value of the corresponding primitive data type. For Byte, Short, Integer, and Long, MIN_VALUE represents the minimum byte, short, int, and long values. For Float and Double, MIN_VALUE represents the minimum positive float and double values. The following statements display the maximum integer (2,147,483,647), the minimum positive float (1.4E-45), and the maximum double floating-point number (1.79769313486231570e+308d). 25

26 26 Conversion Methods Each numeric wrapper class implements the abstract methods doubleValue, floatValue, intValue, longValue, and shortValue, which are defined in the Number class. These methods “convert” objects into primitive type values. 26

27 27 The Static valueOf Methods The numeric wrapper classes have a useful class method, valueOf(String s). This method creates a new object initialized to the value represented by the specified string. For example: Double doubleObject = Double.valueOf("12.4"); Integer integerObject = Integer.valueOf("12"); 27

28 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Parsing String Parsing or syntactic analysis is the process of analyzing a string of symbols, either in natural language or in computer languages, Parsing (Deconstructing or breakdown) is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains the Unicode characters '1' and '0' not the actual number 10. The method Integer.parseInt takes that string value and returns a real number. 28

29 29 The Methods for Parsing Strings into Numbers You have used the parseInt method in the Integer class to parse a numeric string into an int value and the parseDouble method in the Double class to parse a numeric string into a double value. Each numeric wrapper class has two overloaded parsing methods to parse a numeric string into an appropriate numeric value. 29

30 30 Return Value: parseInt(String s): This returns an integer (decimal only). parseInt(int i): This returns an integer, given a string representation of decimal, binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input. Java – parseInt() Method public class Test{ public static void main(String args[]){ int x =Integer.parseInt("9"); double c = Double.parseDouble("5"); int b = Integer.parseInt("444",16); System.out.println(x); System.out.println(c); System.out.println(b); } static in parseIn(String s) static int parseInt(String s, int radix) ParseString

31 31 Automatic Conversion Between Primitive Types and Wrapper Class Types JDK 1.5 allows primitive type and wrapper classes to be converted automatically. For example, the following statement in (a) can be simplified as in (b): 31 Integer[] intArray = {1, 2, 3}; System.out.println(intArray[0] + intArray[1] + intArray[2]); Unboxing

32 32 BigInteger and BigDecimal If you need to compute with very large integers or high precision floating-point values, you can use the BigInteger and BigDecimal classes in the java.math package. Both are immutable. Both extend the Number class and implement the Comparable interface. 32

33 33 BigInteger and BigDecimal BigInteger a = new BigInteger("9223372036854775807"); BigInteger b = new BigInteger("2"); BigInteger c = a.multiply(b); // 9223372036854775807 * 2 System.out.println(c); 33 BigDecimal a = new BigDecimal(1.0); BigDecimal b = new BigDecimal(3); BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP); System.out.println(c); LargeFactorial Run

34 34 import java.math.*; public class LargeFactorial { public static void main(String[] args) { System.out.println("50! is \n" + factorial(50)); } public static BigInteger factorial(long n) { BigInteger result = BigInteger.ONE; for (int i = 1; i <= n; i++) result = result.multiply(new BigInteger(i+"")); return result; } }

35 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. The String Class Constructing a String: String message = "Welcome to Java“; String message = new String("Welcome to Java“); String s = new String(); Obtaining String length and Retrieving Individual Characters in a string String Concatenation (concat) Substrings (substring(index), substring(start, end)) Comparisons (equals, compareTo) String Conversions Finding a Character or a Substring in a String Conversions between Strings and Arrays Converting Characters and Numeric Values to Strings 35

36 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Constructing Strings String newString = new String(stringLiteral); String message = new String("Welcome to Java"); Since strings are used frequently, Java provides a shorthand initializer for creating a string: String message = "Welcome to Java"; 36

37 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Strings Are Immutable A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string? String s = "Java"; s = "HTML"; 37

38 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Trace Code String s = "Java"; s = "HTML"; 38 animation

39 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Trace Code String s = "Java"; s = "HTML"; 39 animation

40 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Examples display s1 == s is false s1 == s3 is true 40 A new object is created if you use the new operator. If you use the string initializer, no new object is created if the interned object is already created.

41 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Trace Code 41 animation

42 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Trace Code 42

43 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Trace Code 43

44 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Replacing and Splitting Strings 44

45 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Examples "Welcome".replace('e', 'A') returns a new string, WAlcomA. "Welcome".replaceFirst("e", "AB") returns a new string, WABlcome. "Welcome".replace("e", "AB") returns a new string, WABlcomAB. "Welcome".replace("el", "AB") returns a new string, WABcome. 45

46 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Splitting a String String[] tokens = "Java#HTML#Perl".split("#", 0); for (int i = 0; i < tokens.length; i++) System.out.print(tokens[i] + " "); 46 Java HTML Perl displays

47 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Matching, Replacing and Splitting by Patterns You can match, replace, or split a string by specifying a pattern. This is an extremely useful and powerful feature, commonly known as regular expression. Regular expression is complex to beginning students. For this reason, two simple patterns are used in this section. Please refer to Supplement III.F, “Regular Expressions,” for further studies. 47 "Java".matches("Java"); "Java".equals("Java"); "Java is fun".matches("Java.*"); "Java is cool".matches("Java.*");

48 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Matching, Replacing and Splitting by Patterns The replaceAll, replaceFirst, and split methods can be used with a regular expression. For example, the following statement returns a new string that replaces $, +, or # in "a+b$#c" by the string NNN. String s = "a+b$#c".replaceAll("[$+#]", "NNN"); System.out.println(s); Here the regular expression [$+#] specifies a pattern that matches $, +, or #. So, the output is aNNNbNNNNNNc. 48

49 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Matching, Replacing and Splitting by Patterns The following statement splits the string into an array of strings delimited by some punctuation marks. String[] tokens = "Java,C?C#,C++".split("[.,:;?]"); for (int i = 0; i < tokens.length; i++) System.out.println(tokens[i]); 49

50 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. StringBuilder and StringBuffer The StringBuilder / StringBuffer class is an alternative to the String class. In general, a StringBuilder/StringBuffer can be used wherever a string is used. StringBuilder/StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created. 50

51 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. StringBuilder Constructors 51

52 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Modifying Strings in the Builder 52

53 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Examples stringBuilder.append("Java"); stringBuilder.insert(11, "HTML and "); stringBuilder.delete(8, 11) changes the builder to Welcome Java. stringBuilder.deleteCharAt(8) changes the builder to Welcome o Java. stringBuilder.reverse() changes the builder to avaJ ot emocleW. stringBuilder.replace(11, 15, "HTML") changes the builder to Welcome to HTML. stringBuilder.setCharAt(0, 'w') sets the builder to welcome to Java. 53

54 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. The toString, capacity, length, setLength, and charAt Methods 54

55 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Problem: Checking Palindromes Ignoring Non-alphanumeric Characters This example gives a program that counts the number of occurrence of each letter in a string. Assume the letters are not case-sensitive. 55 PalindromeIgnoreNonAlphanumeric Run

56 56 import java.util.Scanner; public class PalindromeIgnoreNonAlphanumeric { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter a string System.out.print("Enter a string: "); String s = input.nextLine(); // Display result System.out.println("Ignoring non-alphanumeric characters, \nis " + s + " a palindrome? " + isPalindrome(s)); } /** Return true if a string is a palindrome */ public static boolean isPalindrome(String s) { // Create a new string by eliminating non-alphanumeric chars String s1 = filter(s); // Create a new string that is the reversal of s1 String s2 = reverse(s1); // Compare if the reversal is the same as the original string return s2.equals(s1); } /** Create a new string by eliminating non-alphanumeric chars */ public static String filter(String s) { // Create a string builder StringBuilder stringBuilder = new StringBuilder(); // Examine each char in the string to skip alphanumeric char for (int i = 0; i < s.length(); i++) { if (Character.isLetterOrDigit(s.charAt(i))) { stringBuilder.append(s.charAt(i)); } } // Return a new filtered string return stringBuilder.toString(); } /** Create a new string by reversing a specified string */ public static String reverse(String s) { StringBuilder stringBuilder = new StringBuilder(s); stringBuilder.reverse(); // Invoke reverse in StringBuilder return stringBuilder.toString(); } }

57 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Regular Expression Syntax 57 Appendix H


Download ppt "Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Chapter 10 Thinking in Objects 1."

Similar presentations


Ads by Google