Chapter 10. Object-Oriented Thinking

Similar documents
Chapter 10 Thinking in Objects. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.

Chapter 10 Thinking in Objects. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

C08c: A Few Classes in the Java Library (II)

Introduction to Java Programming Comprehensive Version

Abstract Classes Interfaces

Chapter 9 Abstract Classes and Interfaces

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

JAVA.LANG.INTEGER CLASS


ITI Introduction to Computing II

ITI Introduction to Computing II

Introduction to Programming Using Python Lecture 4. Dr. Zhang COSC 1437 Fall, 2018 October 11, 2018

PIC 20A Number, Autoboxing, and Unboxing

JAVA WRAPPER CLASSES

CSC Java Programming, Fall Java Data Types and Control Constructs

Java Classes: Math, Integer A C S L E C T U R E 8

Introduction to Programming Using Java (98-388)

Classes and Objects Miscellany: I/O, Statics, Wrappers & Packages. CMSC 202H (Honors Section) John Park

H212 Introduction to Software Systems Honors

Thinking in Objects. CSE 114, Computer Science 1 Stony Brook University

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

CST141 Thinking in Objects Page 1

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Ahmadu Bello University Department of Mathematics First Semester Examinations June 2014 COSC211: Introduction to Object Oriented Programming I

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Lecture Notes Chapter #9_c Abstract Classes & Interfaces

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

(b) This is a valid identifier in Java: _T_R-U_E_. (c) This is a valid identifier in Java: _F_A_L_$_E_

Topics. The Development Process

Programming in the Large II: Objects and Classes (Part 1)

CEN 414 Java Programming

Lecture 8. Reviewing Methods; Wrapper Classes

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2 Elementary Programming

Encapsulation in Java

Chapter 2 Elementary Programming

Abstract Classes and Interfaces. CSE 114, Computer Science 1 Stony Brook University

Programming with Java

String is a Class; Quoted Text is an Object

Beginning Programming (Java) Test 2/Version 1 CMSC 1513 Spring 2013

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Review of Java. or maybe not

Midterm Examination (MTA)

Unit 3 INFORMATION HIDING & REUSABILITY. Interface:-Multiple Inheritance in Java-Extending interface, Wrapper Class, Auto Boxing

Lab Exercise 1. Objectives: Part 1. Introduction

Introduction to Computer Programming

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Java Programming Lecture 10

Data Types and Variables

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Fundamentals of Programming Data Types & Methods

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

Lecture 4. Strings, Wrappers, & Containers

More About Objects and Methods

More About Objects and Methods. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

Chapter 5. Defining Classes II. Slides prepared by Rose Williams, Binghamton University

COMPUTER APPLICATIONS

Formatting Output & Enumerated Types & Wrapper Classes

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2018 Instructors: Bill & Bill

1 Short Answer (5 Points Each)

Chapter 2 Primitive Data Types and Operations. Objectives

Chapter 13 Abstract Classes and Interfaces

JAVA OPERATORS GENERAL

Value vs. reference semantics

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

ICSE Class 10 Computer Applications ( Java ) 2014 Solved Question Paper

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014

JAVA Programming Concepts

Operators and Expressions

Chapter 2 Elementary Programming

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

Introduction to Inheritance

Tutorial 03. Exercise 1: CSC111 Computer Programming I

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Chapter 5. Defining Classes II. Copyright 2016 Pearson Inc. All rights reserved.

TeenCoder : Java Programming (ISBN )

CS162: Introduction to Computer Science II. Primitive Types. Primitive types. Operations on primitive types. Limitations

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

OBJECT ORIENTED PROGRAMMING IN JAVA

Defining Classes II CHAPTER

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

Darshan Institute of Engineering & Technology for Diploma Studies Unit 2

[TAP:AXETF] Inheritance

Motivations 9/14/2010. Introducing Programming with an Example. Chapter 2 Elementary Programming. Objectives

Computer Science II (20082) Week 1: Review and Inheritance

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn how to describe objects and classes and how to define classes and create objects

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

Object Oriented Programming. Java-Lecture 1

DM503 Programming B. Peter Schneider-Kamp.

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Building Java Programs

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Object Oriented Programming. Java-Lecture 6 - Arrays

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban

Transcription:

Chapter 10 Object-Oriented Thinking 1

Class Abstraction and Encapsulation Class abstraction is the separation of class implementation details from the use of the class. The class creator provides a description of the class to let users know how to use the class. Users of the class do not need to know the class implementation details. Thus, implementation details are encapsulated (hidden) from the user. Class implementation is a black box hidden from the clients Class Class Contract (Signatures of public methods and public constants) Clients use the class through the contract of the class 2

Visibility Modifiers and Abstraction public private Variables Violate encapsulation Enforce encapsulation Methods Provide services to clients of the class Support other methods in the class

Designing Class Loan Problem Statement: A Loan is characterized by: - borrowed amount (variable) - interest rate (variable) - start date (variable) - loan duration (years) (variable) - monthly payment (need to be computed) (method) - total payment (need to be computed) (method) Each real-life loan is a loan object with specific values for those characteristics. (e.g., car loan, mortgage, personal loan, etc.) To program the Loan concept, we need to define class Loan with data fields (attributes) and methods. 4

Designing the Loan Class To achieve encapsulation in the class design, we need the following: 1. Define all variables to be private. No exceptions! 2. Define public methods (getters and setters) for each private variable that users of the class need to access. 3. Methods that users of the class need to know about (make use of) must be defined as public. 4. Support methods must be defined as private. Note: All class methods have access to all of its variables. 5

UML modeling of class Loan Loan -annualinterestrate: double -numberofyears: int -loanamount: double -loandate: Date +Loan() +Loan(annualInterestRate: double, numberofyears: int, loanamount: double) +getannualinterestrate(): double +getnumberofyears(): int +getloanamount(): double +getloandate(): Date +setannualinterestrate( annualinterestrate: double): void +setnumberofyears( numberofyears: int): void +setloanamount( loanamount: double): void +getmonthlypayment(): double +gettotalpayment(): double The annual interest rate of the loan (default: 2.5). The number of years for the loan (default: 1) The loan amount (default: 1000). The date this loan was created. Constructs a default Loan object. Constructs a loan with specified interest rate, years, and loan amount. Returns the annual interest rate of this loan. Returns the number of the years of this loan. Returns the amount of this loan. Returns the date of the creation of this loan. Sets a new annual interest rate to this loan. Sets a new number of years to this loan. Sets a new amount to this loan. Returns the monthly payment of this loan. Returns the total payment of this loan. Class Loan and class TestLoanClass start on page 367. 6

Class Loan Constructor Methods // see complete class code on page 368 // Default constructor with default values public Loan() { this(2.5, 1, 1000); // calls the second constructor to create // a loan object with default values. // This is same as: // annualinterestrate = 2.5; // numberofyears = 1; // loanamount = 1000; // Construct a loan with specified rate, number of years, and amount public Loan(double annualinterestrate, int numberofyears, double loanamount) { this.annualinterestrate = annualinterestrate; this.numberofyears = numberofyears; this.loanamount = loanamount; loandate = new java.util.date(); // creates date object } 7

Class TestLoanClass import java.util.scanner; public class TestLoanClass { public static void main(string[] args) { // Main method Scanner input = new Scanner(System.in); // Create a Scanner // Enter yearly interest rate System.out.print("Enter yearly interest rate, for example, 8.25: "); double annualinterestrate = input.nextdouble(); // Enter number of years System.out.print("Enter number of years as an integer: "); int numberofyears = input.nextint(); // Enter loan amount System.out.print("Enter loan amount, for example, 120000.95: "); double loanamount = input.nextdouble(); // Create Loan object Loan loan = new Loan(annualInterestRate, numberofyears, loanamount); // Display loan date, monthly payment, and total payment System.out.println( "The was loan created on: " + loan.getloandate().tostring() + "\n" + "The monthly payment is: " + loan.getmonthlypayment() + "\n" + "The total payment is: " + loan.gettotalpayment()); } } 8

Another OO Example: Class BMI BMI -name: String -age: int -weight: double -height: double +BMI(name: String, age: int, weight: double, height: double) +BMI(name: String, weight: double, height: double) +getbmi(): double +getstatus(): String +getname(): String +getage(): int +getweight(): double +getheight(): double The name of the person. The age of the person. The weight of the personin pounds. The height of the personin inches. Creates a BMI object with the specified name, age, weight, and height. Creates a BMI object with the specified name, weight, height, and a default age 20 Returns the BMI Returns the BMI status (e.g., normal, overweight, etc.) Return name Return age Return weight Return height 9

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; } // constructors 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); // getters public String getname() { return name; } public int getage() { return age; } public double getweight() { return weight; } public double getheight() { return height; } // continue next slide Class BMI this.name = name; this.age = 20; this.weight = weight; this.height = height; 10

Class BMI // compute PMI public double getbmi() { } double bmi = weight * KILOGRAMS_PER_POUND / ((height * METERS_PER_INCH) * (height * METERS_PER_INCH)); return Math.round(bmi * 100) / 100.0; // determine status public String getstatus() { double bmi = getbmi(); } } if (bmi < 18.5) return "Underweight"; else if (bmi < 25) return "Normal"; else if (bmi < 30) return "Overweight"; else return "Obese"; 11

The Test Program 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()); ----jgrasp exec: java UseBMIClass The BMI for John Doe is 20.81 Normal The BMI for Peter King is 30.85 Obese ----jgrasp: operation complete. 12

Wrapper Classes Java primitive types are NOT objects. Often we need to treat primitive values as objects. The solution is to convert a primitive type value, such as 45, to an object that hold value 45. Java provides Wrapper Classes for all primitive types. 13

Wrapper Classes Boolean Character Short Byte Integer Long Float Double Note: (1) The wrapper classes do not have no-argument constructors. (2) The instances (objects) of all wrapper classes are immutable. That is, their internal values cannot be changed once the objects are created. (3) A wrapper class object contains one value of the class type. 14

The Integer and Double Classes -value: int +MAX_VALUE: int +MIN_VALUE: int java.lang.integer -value: double +MAX_VALUE: double +MIN_VALUE: double java.lang.double +Integer(value: int) +Integer(s: String) +bytevalue(): byte +shortvalue(): short +intvalue(): int +longvlaue(): long +floatvalue(): float +doublevalue():double +compareto(o: Integer): int +tostring(): String +valueof(s: String): Integer +valueof(s: String, radix: int): Integer +parseint(s: String): int +parseint(s: String, radix: int): int +Double(value: double) +Double(s: String) +bytevalue(): byte +shortvalue(): short +intvalue(): int +longvlaue(): long +floatvalue(): float +doublevalue():double +compareto(o: Double): int +tostring(): String +valueof(s: String): Double +valueof(s: String, radix: int): Double +parsedouble(s: String): double +parsedouble(s: String, radix: int): double 15

Numeric Wrapper Class Constructors We can construct a wrapper object either from: 1) primitive data type value 2) string representing the numeric value The constructors for classes Integer and Double are: public Integer(int value) public Integer(String s) public Double(double value) public Double(String s) Examples: Integer intobject1 = new Integer(90); Integer intobject2 = new Integer("90"); Double doubleobject1 = new Double(95.7); Double doubleobject2 = new Double("95.7"); // Similar syntax for Float, Byte, Short, and Long types. 16

Numeric Wrapper Class Constants Each numerical wrapper class has 2 constants: MAX_VALUE: represents the maximum value of the type. MIN_VALUE: represents the minimum value of the type. Examples: System.out.println("Max integer is: " + Integer.MAX_VALUE); System.out.println("Min integer is: " + Integer.MIN_VALUE); System.out.println("Max float is: " + Float.MAX_VALUE); System.out.println("Min float is: " + Float.MIN_VALUE); System.out.println("Max short is: " + Short.MAX_VALUE); System.out.println("Min short is: " + Short.MIN_VALUE); System.out.println("Max byte is: " + Byte.MAX_VALUE); System.out.println("Min byte is: " + Byte.MIN_VALUE); 17

Conversion Methods Each numeric wrapper class implements conversion methods that convert an object of a wrapper class to a primitive type: doublevalue(), floatvalue(), intvalue() longvalue(), and shortvalue(). Examples: Double myvalue = new Double(97.50); System.out.println(myValue.intValue()); //gives 97 System.out.println(myValue.floatValue()); //gives 97.5 System.out.println(myValue.shortValue()); //gives 97 System.out.println(myValue.longValue()); //gives 97 18

The Static valueof Methods The numeric wrapper classes have a useful class method: valueof(string s) This method creates a new object initialized with the value represented by the specified string. Examples: Double doubleobject = Double.valueOf("95.79"); Integer integerobject = Integer.valueOf("86"); Float floatobject = Float.valueOf("95.54"); Long longobject = Long.valueOf("123456789"); Short shortobject = Short.valueOf("123"); Byte byteobject = Byte.valueOf("101,2); //value is 5 19

Methods for Parsing Strings into Numbers Parsing methods allow us to pars numeric strings into numeric types. Each numeric wrapper class has two overloaded parsing methods: Public static int parseint(string s) Public static int parseint(string s, int radix) Examples: int A = Integer.parseInt("25"); //A has int value 25 System.out.println(A); int B = Integer.parseInt("110",2); //B has int value 6 System.out.println(B); int C = Integer.parseInt("25",8); //C has int value 21 System.out.println(C); int D = Integer.parseInt("25",10); //D has int value 25 System.out.println(D); int E = Integer.parseInt("25",16); //E has int value 37 System.out.println(E); 20

Automatic Conversion Java allows primitive type and wrapper classes to be converted automatically. Integer[] intarray = {new Integer(2), new Integer(4), new Integer(3)}; Equivalent Integer[] intarray = {2, 4, 3}; (a) boxing (b) Integer[] intarray = {1, 2, 3}; System.out.println(intArray[0] + intarray[1] + intarray[2]); Unboxing 21

BigInteger and BigDecimal Classes To work with very large integers or high precision floating-point values, you can use the BigInteger and BigDecimal classes in the java.math package. Examples: BigInteger biga = new BigInteger("12345678923456789"); BigInteger bigb = new BigInteger("7"); BigDecimal bigc = new BigDecimal("1245.56789"); BigDecimal bigd = new BigDecimal("2"); System.out.println(bigA.multiply(bigB)); System.out.println(bigC.divide(bigD, 20,BigDecimal.ROUND_UP)); The output is: 86419752464197523 //too large to fit in long type variable 622.78394500000000000000 //high precision, 20 decimal places 22

The String Class Revisited A String object is immutable; its contents cannot be changed. The following code does NOT change the content of string s. String s = "Java"; s = "HTML"; After executing String s = "Java"; After executing s = "HTML"; s : String Java s : String Java This string object is now unreferenced Contents cannot be changed : String HTML 23

End of Chapter 10 24