CST141 Thinking in Objects Page 1

Similar documents
JAVA WRAPPER CLASSES

CST141--Inheritance 2

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Full file at

Introduction to Programming Using Java (98-388)

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

CT 229 Fundamentals of Java Syntax

CSC Java Programming, Fall Java Data Types and Control Constructs

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Data Types Reference Types

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Course PJL. Arithmetic Operations

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Chapter 4 Defining Classes I

Chapter 6 Introduction to Defining Classes

Introduction to Classes and Objects

Chapter 2: Using Data

Chapter 2: Java Fundamentals

8/23/2014. Chapter Topics. Chapter Topics (2) Parts of a Java Program. Parts of a Java Program. Analyzing The Example. Chapter 2: Java Fundamentals

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Week 7 - More Java! this stands for the calling object:

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

CSE1710. Big Picture. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

In this lab, you will be given the implementation of the classes GeometricObject, Circle, and Rectangle, as shown in the following UML class diagram.

Array. Prepared By - Rifat Shahriyar

19. GUI Basics. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Chapter 2: Using Data

Index COPYRIGHTED MATERIAL

PIC 20A Number, Autoboxing, and Unboxing

CSE1710. Big Picture. Today is last day covering Ch 6. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

CS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces

Lesson 3: Accepting User Input and Using Different Methods for Output

Strings! Today! CSE String Methods!

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

We now start exploring some key elements of the Java programming language and ways of performing I/O

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

JAVA GUI PROGRAMMING REVISION TOUR III

ITI Introduction to Computing II

Java Programming Lecture 7

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

ITI Introduction to Computing II

EECS168 Exam 3 Review

Defining Classes and Methods

Objects and Classes. Basic OO Principles. Classes in Java. Mark Allen Weiss Copyright 2000

Java Programming Lecture 6

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Chapter 02: Using Data

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

A variable is a name for a location in memory A variable must be declared


Data Structures (list, dictionary, tuples, sets, strings)

Objects and Iterators

String related classes

Chapter 15: Object Oriented Programming

JOptionPane Dialogs. javax.swing.joptionpane is a class for creating dialog boxes. Has both static methods and instance methods for dialogs.

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 7 OBJECTS AND CLASSES

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

Full file at

Java Programming Fundamentals. Visit for more.

Object Oriented Design

More About Objects and Methods

CST242 Strings and Characters Page 1

Guessing Game with Objects

CS304 Object Oriented Programming Final Term

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Object-Oriented Programming Concepts

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

CS162: Introduction to Computer Science II

Defining Classes and Methods

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

Lecture 7: Classes and Objects CS2301

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

5. Defining Classes and Methods

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

CHAPTER 7 OBJECTS AND CLASSES

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Chapter 2 ELEMENTARY PROGRAMMING

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Chapter 1 Getting Started

Programming II (CS300)

COMP 250 Winter 2011 Reading: Java background January 5, 2011

CS 106 Introduction to Computer Science I

JAVA Programming Fundamentals

Addendum File Web Design and Development (CS506)

More About Objects and Methods. Objectives. Outline. Chapter 6

More About Objects and Methods

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

TeenCoder : Java Programming (ISBN )

Motivations. Chapter 13 Abstract Classes and Interfaces

Transcription:

CST141 Thinking in Objects Page 1 1 2 3 4 5 6 7 8 Object-Oriented Thinking CST141 Class Abstraction and Encapsulation Class abstraction is the separation of class implementation from class use It is not necessary to understand the class s implementation (its code ) to use it in classes Class encapsulation means that the details of implementation are hidden from the user The class interface makes it possible to use a class without knowledge of its implementation Interface vs. Implementation (Page 1) The interface (the class documentation ) consists of: The name of the class A general description of the class A list of constructors and methods The return values and parameters for constructors and methods The description of the purpose of each constructor and method The constants and any other components Interface vs. Implementation (Page 2) The interface does not include the class implementation: The private data fields Any public methods The bodies (source code) for each method Documentation Document everything Write your comments first Before you write the method If you do not know what to write, you probably do not understand fully what the method is supposed to do Writing Class Documentation Your own classes can be documented the same way as are Java API library classes Use your classes to create an interface, e.g. library class Others should be able to use your classes by reading the interface (documentation) without access to the implementation Elements of Documentation (Page 1) Documentation for a class should include: The class name (and inheritance hierarchy) A comment describing the overall purpose, function, and characteristics of the class A version number The name of the author or authors Documentation for each constructor and each method in the class Elements of Documentation (Page 2) Documentation for methods (all methods including constructors ) should include: 9

CST141 Thinking in Objects Page 2 8 Elements of Documentation (Page 2) Documentation for methods (all methods including constructors ) should include: 8 The method name, as well as a comment describing its purpose and function 9 9 10 10 11 11 12 12 13 13 14 14 15 15 16 16 Documentation for each constructor and each method in the class The parameter names and types, including a description The method name, as well as a comment describing its purpose and function The return type, including a description The parameter names and types, including a description The The Javadoc return Utility type, including a (Page description 1) The Javadoc.exe Javadoc Utility is a standard, convenient (Page 1) tool to document Java code (part of Java JDK) Requires special formatting of comments Javadoc.exe is a standard, convenient tool to document Java code (part of Java JDK) This utility reads the formatted comments, and automatically generates an HTML Requires special formatting of comments document based on those comments This utility reads the formatted comments, and automatically generates an HTML The HTML files provide convenience of hyperlinks from one document to another, as document based on those comments well as within each document The HTML files provide convenience of hyperlinks from one document to another, as The well Javadoc as within Utility each document (Page 2) The Two Javadoc kinds of Utility Javadoc comments: (Page 2) Class-level comments provides overall description of the classes Two kinds of Javadoc comments: Member-level comments describes the purpose(s) of the members (e.g. usually the Class-level comments provides overall description of the classes methods) Member-level comments describes the purpose(s) of the members (e.g. usually the Both types of comments always start with the characters /** and end with methods) Both Class-Level types of Comments comments always (Page start with 1) the characters /** and end with Class-Level Class-level comments Comments provide an (Page overall 1) description of the class Placed just above class header Class-level comments provide an overall description of the class May not be followed by any other elements before the class header (e.g. import) Placed just above class header Generally contain author and version number tags, and a description of the class May not be followed by any other elements before the class header (e.g. import) Generally Class-Level contain Comments author and version (Page 2) number tags, and a description of the class Class-Level Example class-level Comments comment: (Page 2) /** Example class-level comment: * The Payee class calculates payroll /** * for regular and overtime workers. The Payee class calculates payroll * Users update data fields by calling for regular and overtime workers. * the sethoursworked() and setpayrate() Users update data fields by calling * methods. the sethoursworked() and setpayrate() * methods. * @author Carl B. Struck * @version 1.0 @author Carl B. Struck * @version 1.0 public class Payee { public class Payee Tags { Tags Tags are formatting elements that start with ampersand (@) character and are formatted in the documentation by Javadoc.exe utility Tags are formatting elements that start with ampersand (@) character and are The @author tag describes the author(s) formatted in the documentation by Javadoc.exe utility @author Carl B. Struck The @author tag describes the author(s) The @version tag describes the version number or similar information @author Carl B. Struck @version 1.0 The @version tag describes the version number or similar information Class @version Payee 1.0 (Documentation) Member-Level Comments (Page 1) Member-level comments describe the fields, methods, and constructors Placed directly above each method header Member-Level Comments (Page 2) Member-level tags may include: The @param tag which describes each of the method s required parameters

14 Class CST141 Thinking in /** Payee (Documentation) Objects Page 3 14 15 Member-Level * Mutator method Comments for the hours (Page worked 1) Member-level * data field. Validates comments that describe hours the fields, methods, and constructors 15 Placed * worked directly is between above each 0.25 and method 60.0. header * 16 Placed Member-Level directly Comments above each method (Page header 2) * @param hoursworked the employee number Member-Level Member-level 16 * tags Comments of may hours include: worked (Page 2) Member-level The @param tag which describes each of the method s required parameters tags may include: public The @return The @param void sethoursworked(int tag describes the tag which describes hoursworked) return value of a non-void method each of the method s required parameters { The exceptions which the method throws (Chapter 14) The @return tag describes the return value of a non-void method 17 Member-Level The exceptions Comments which the method (Page throws 3) 19 Member-Level Comments-- @param Tag (Chapter 14) 17 Member-Level The @param tag Comments describes each (Page of the 3) method s required parameters 20 Member-Level There may be Comments more than one (Page @param 5) for a method if it takes more than one The The @param tag describes each of the method s required parameters parameter @return tag describes the return value of a non-void method There may be more than one @param for a method if it takes more than one First word always is the parameter variable name and it will be followed by a parameter @return hyphen Employee (-) in the number generated of documentation hours worked as a double First word always is the parameter variable name and it will be followed by a Example: 21 Member-Level hyphen (-) in Comments the generated (Page documentation 6) @param hoursworked the employee number of hours worked A member-level Example: comment with a @return tag: 18 Member-Level /** @param hoursworked Comments the employee (Page 4) number of hours worked 18 Member-Level Member-level * Accessor method comment Comments for with the hours a (Page @param worked 4) tag: /*** data field. Member-level comment with a @param tag: * Mutator method for the hours worked /** * data @return field. Employee Validates number that hours of hours Mutator method for the hours worked * worked worked is between as a double 0.25 and 60.0. data field. Validates that hours worked is between 0.25 and 60.0. public * @param String hoursworked gethoursworked() the employee number {* of hours worked @param hoursworked the employee number 22 Member-Level * Comments-- of hours worked @param Tag public void sethoursworked(int hoursworked) 23 Class { Time (Page 1) public void sethoursworked(int hoursworked) 19 24 Member-Level Class { Time Comments-- @param (Page Tag2) 19 20 25 20 26 27 21 21 28 29 30 31 22 32 22 23 23 24 24 25 25 26 33 Member-Level Class Time Comments (Page (Page 5) 3) The Class @return Time tag describes the return (Page value 4) of a non-void method MiniQuiz @return(part Employee 2) from number previous of hours chapter worked as a double Continue the Book class ( interfaces-miniquiz ) by adding get (accessor) methods for Member-Level the two data fields Comments (Page 6) A Create member-level Javadoc documentation comment with a for @return the class: tag: /** A class-level comment with @author and @version tags (should already exist) * Member-level Accessor method comments for the for hours both worked constructors and all methods with @parameter * and data @return field. tags where appropriate * Class Book (interfaces-miniquiz-part2) (Page 1) * @return Employee number of hours Class * Book worked (interfaces-miniquiz-part2) as a double (Page 2) Class Book (interfaces-miniquiz-part2) (Page 3) public String gethoursworked() Class { Book (interfaces-miniquiz-part2) (Page 4) Member-Level Object Composition Comments-- @param Tag Class Composition Time is the relationship in which (Page one 1) object contains another object, e.g.: A Date object instantiated within another class Class A String Time object instantiated in another (Page class 2) Class Any Time object of a programmer-defined (Page class 3) that is instantiated within another class Most professional applications include a large number of classes working together Class Time (Page 4) Cohesion (Page 1)

30 CST141 Thinking in Objects Page 4 31 32 33 34 35 36 37 38 39 A Date object instantiated within another class A String object instantiated in another class Any object of a programmer-defined class that is instantiated within another class Most professional applications include a large number of classes working together Cohesion (Page 1) Cohesion is a measure of the number and the diversity of tasks for which a single unit is responsible If each unit is responsible for one single logical task, we say it has high cohesion Cohesion applies to classes and methods Cohesion (Page 2) High cohesion makes it easier to: Understand what a class or method does Give it a descriptive name Reuse the classes and/or methods Cohesion (Page 3) Cohesion of classes: Classes should represent one single, well defined entity and is the single location were all that functionality is managed Cohesion of classes will result in better maintainability, reusability, and reliability Cohesion (Page 4) Cohesion of methods: A method should be responsible for one and only one well defined task Easier to understand short cohesive methods rather than longer methods that carry out several tasks Even if the statements for several tasks could have been coded in a single method Also a method s name should clearly state its function Consistency (Page 1) Follow Java standards (conventions used by most programmers in industry): Choose informative names for classes, data fields and methods Do not choose different names for similar entities and operations Use the this reference for data fields in constructors and set methods with matching parameter names This also is true in Java API classes, e.g. the String, StringBuilder and StringBuffer classes all have a length method with identical functionality Consistency (Page 2) Follow Java standards (conventions used by most programmers in industry) (con.): Place data field declarations before constructors Place constructors before methods Provide a no-argument constructor for defining a default instance of the class Or have a good reason why not and document the reason, e.g. immutable objects Encapsulation (Page 1) Encapsulation is achieved by making instance variables private Also called information hiding 40

CST141 Thinking in Objects Page 5 39 40 41 42 43 44 45 46 47 Only what a class can do should be visible to the outside, not how it does it Encapsulation (Page 2) Through a public interface the private data can be used by the client class without corrupting that data Only the class own methods may directly inspect or manipulate its data fields Protects data from the client but still allows the client to access the data Makes the class easier to maintain since the functionality is managed in just one place Encapsulation (Page 3) Encapsulation is achieved by: Making data fields (instance and static variables) private, and Having public accessor and mutator methods that give access to the data fields (of which the client does not know how they function) Clarity Class members should be clear and easy to understand, e.g.: Property values may be assigned in any order Methods should be intuitive, e.g.: Method substring(int beginindex, int endindex) is not since the string returned stops at endindex 1 Do not declare data fields that can be derived from other data fields, e.g.: In the Payee class grosspay is calculated from hoursworked and payrate Completeness Classes are used by many clients and should be useful for a wide range of applications Provide a wide variety of properties and methods to meet all possible needs E.g. the String class has more than 40 methods Instance vs. Static (Page 1) A variable or method that is dependent on a specific instance of the class should be an instance variable or method Instance vs. Static (Page 2) A variable that is shared (one RAM location) by all instances of a class should be static Static variables usually should be handled by static methods Reference static members with the class name, e.g. JOptionPane.showMessageDialog() Do not pass parameters for static variables to constructors which always are used to create an instance; rather include a static set method The JOptionPane Class (Page 1) Class from the Java API library providing simple to use popup dialogs to prompt users for a value or to display information A member of the javax.swing class: import javax.swing.joptionpane; The JOptionPane Class (Page 2) JOptionPane class can seem complex, but most methods are one-line calls to one of

CST141 Thinking in Objects Page 6 47 48 49 50 51 52 53 54 the four (4) static showxxxdialog methods Two of the methods are: showinputdialog prompts for some input showmessagedialog a message that tells the user about something that has happened The JOptionPane Class (Page 3) These two methods showinputdialog and showmessagedialog are static: public static void showmessagedialog( Component parent, Object message ) The syntax to call these methods uses the class name, not an object name), e.g. JOptionPane.showMessageDialog( null, pay1.tostring() ); The JOptionPane Class (Page 4) JOptionPane method calls pause program execution (blocks the caller until the user s interaction is complete) The Java API documentation for the class JOptionPane is located on-line at: http://docs.oracle.com/javase/7/docs/api/javax/swing/joptionpane.html The showmessagedialog Method (Page 1) Displays output in a message dialog window The showmessagedialog is a method of the predefined JOptionPane class contained in the Java API library Alternative to println method which instead allows GUI (graphical user interface) output The showmessagedialog Method (Page 2) Takes two required parameters: The first is the keyword null The second is the output message (String, etc.) Format: JOptionPane.showMessageDialog(null, message); JOptionPane.showMessageDialog(null, pay1.tostring() ); The showinputdialog Method (Page 1) Accepts a String typed input from users in a textbox within the dialog window The showinputdialog is a member of the JOptionPane class Alternative to Scanner object which instead allows for GUI input The showinputdialog Method (Page 2) The only required argument is a message A promp that tells the user what value should be keyed into the textbox The return value of the method is a String that is usually assigned to a variable The showinputdialog Method (Page 3) Format: JOptionPane.showInputDialog(message); String input = JOptionPane.showInputDialog( "Enter hours worked" ); 55

54 CST141 Thinking in Objects Page 7 57 55 58 59 56 60 61 62 63 57 64 58 59 60 65 61 62 63 64 66 65 67 68 66 Examples: Integer myintegerobject = new Integer(myInteger); Integer myintegerobject = new Integer(40); Wrapper Classes (Page 3) Wrapper classes do not have no-argument constructors since they are immutable Wrapper Once instantiated Classes their values (Page are unchangeable 1) Primitive Each wrapper types class (byte, includes short, int, a conversion long, float, method, double, e.g. boolean doublevalue(), and char) are floatvalue(), not objects Wrapper intvalue(), classes, longvalue(), which shortvalue() allow primitives to be treated like objects, exist for every Each primitive: wrapper class includes compareto() and valueof() methods Class Byte, WrapperDemo Short, Integer, Long, Float, (Page Double, 1) Boolean and Character Located in the java.lang package so they do not need to be imported Class WrapperDemo (Page 2) Wrapper Classes (Page 2) Class WrapperDemo (Page 3) Instantiated wrapper objects can hold and manipulate primitive values, e.g.: Class WrapperClass WrapperDemo object = new WrapperConstructor(primitiveValue); (Page 4) Examples: Class WrapperDemo (Page 5) Integer myintegerobject = new Integer(myInteger); Class Integer WrapperDemo myintegerobject = new (Page Integer(40); 6) Wrapper Classes (Page 4) All Java wrapper classes (except Character) have parse methods that can convert String format of a number to numeric value: Byte.parseByte(string) Short.parseShort(string) Integer.parseInt(string) Long.parseLong(string) Float.parseFloat(string) Double.parseDouble(string) Boolean.parseBoolean(string) The Integer.parseInt Method A method from wrapper class Integer that converts String values to int type May be necessary when an input method (e.g. showinputdialog()) returns a String Format: Integer.parseInt(string) int age = Integer.parseInt(stringAge); The Double.parseDouble Method A method from wrapper class Double that converts String values to double type May be necessary when an input method returns a String Format: double.parsedouble(string) double hoursworked = Double.parseDouble(stringHours); Return Values as Arguments to Another Method (Page 1) When the return value (result) of one method will serve as an argument to the next method Rather than storing the return value in a separate variable A common Java programmer practice is to insert the entire the first method call into the argument parentheses of the second method Return Values as Arguments to Another Method (Page 2) Instead of: String stringhours = JOptionPane.showInputDialog ("Enter hours worked");

CST141 Thinking in Objects Page 8 68 69 70 71 72 73 Instead of: String stringhours = JOptionPane.showInputDialog ("Enter hours worked"); double hoursworked = Double.parseDouble(stringHours); Rather: double hoursworked = Double.parseDouble( JOptionPane.showInputDialog( "Enter hours worked") ); 74 75 76 77 78 79 80 81 String constants enclosed in double quotes E.g String firstname = "Charles"; Character Representation All characters (whether in a char or a String) are represented as a binary integer value between zero (0) and 65,535 Requires two bytes (16 bits) of storage in RAM or on a disk The highest 16 digit binary number is 11111111 11111111 or 65,535 The integer storage values are know as Unicode (formerly ANSI one byte) The Unicode Table Complete Unicode specification can be found at: