Utilities (Part 2) Implementing static features 1.

Slides:



Advertisements
Similar presentations
COSC 2006 Data Structures I Instructor: S. Xu URL:
Advertisements

Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
Java Basics M Taimoor Khan
Utilities (Part 3) Implementing static features 1.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
26-Jun-15 Methods. About methods A method is a named group of declarations and statements If a method is in the same class, you execute those declarations.
Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
1 Further OO Concepts II – Java Program at run-time Overview l Steps in Executing a Java Program. l Loading l Linking l Initialization l Creation of Objects.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 More Class Design Lecture 13, Wed Feb
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
3.1 Documentation & Java Language Elements Purpose of documentation Assist the programmer with developing the program Assist other programers who.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
Writing JavaDocs Mimi Opkins CECS 274 Copyright (c) Pearson All rights reserved.
Classes CS 21a: Introduction to Computing I First Semester,
1 Introduction Modules  Most computer programs solve much larger problem than the examples in last sessions.  The problem is more manageable and easy.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Vladimir Misic: Java1 Basic Java Syntax The java language will be described by working through its features: –Variable types and expressions.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
Documentation and Programming Style Appendix A © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Javadoc Comments.  Java API has a documentation tool called javadoc  The javadoc tool is used on the source code embedded with javadoc-style comments.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
Documentation javadoc. Documentation not a programmer's first love lives in a separate file somewhere usually a deliverable on the schedule often not.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
RECITATION 4. Classes public class Student { } Data Members public class Student { private String name; public String id; }
CSC 142 Computer Science II Zhen Jiang West Chester University
Session 7 Methods Strings Constructors this Inheritance.
JavaDoc and Contracts Spring Documenting Contracts with JavaDoc Contract model for methods Preconditions Postconditions JavaDoc Industry standard.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
Inheritance (Part 2) Notes Chapter KomondorBloodHound PureBreedMix Dog Object Dog extends Object PureBreed extends Dog Komondor extends PureBreed.
Methods: A Deeper Look. Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
Object Oriented Programming with Java 03 - Introduction to Classes and Objects.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
1  lecture slides online
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
Puzzle 1  what does the following program print? public class Puzzle01 { public static void main(String[] args) { System.out.print("C" + "S" + "E"); System.out.println('1'
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Objects and Classes.
Class Design I Class Contracts Readings: 2 nd Ed: Section 9.5, Advanced Topic nd Ed: Section 8.5, Advanced Topic 8.2 Some ideas come from: “Practical.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CSE 1030: Implementing Static Features Mark Shtern.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Methods.
Utilities (Part 2) Implementing static features 1.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
3-July-2002cse142-D2-Methods © 2002 University of Washington1 Methods CSE 142, Summer 2002 Computer Programming 1
Methods.
Design by Contract Fall 2016 Version.
Classes & Objects: Examples
CSE 1030: Implementing Non-Static Features
CSE 1020:Programming by Delegation
Group Status Project Status.
Implementing Non-Static Features
Defining Classes and Methods
JavaDoc and Contracts Fall 2008.
Object Oriented Programming in java
Defining Classes and Methods
Classes CS 21a: Introduction to Computing I
Implementing static features
Corresponds with Chapter 5
Presentation transcript:

Utilities (Part 2) Implementing static features 1

Goals for Today 2  learn about preventing class instantiation  learn what a utility is in Java  learn about implementing methods  static methods  pass-by-value  Javadoc

Puzzle 2 3  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000; final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000; System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY); }

4  prints 5  the problem occurs because the expression 24 * 60 * 60 * 1000 * 1000 evaluates to a number bigger than int can hold  86,400,000,000 > 2,147,483,647 (Integer.MAX_VALUE)  called overflow  notice that the numbers in the expression are of type int  Java will evaluate the expression using int even though the constant MICROS_PER_DAY is of type long  solution: make sure that the first value matches the destination type 24L * 60 * 60 * 1000 * 1000

new DistanceUtility Objects 5  our DistanceUtility API does not expose a constructor  but DistanceUtility u = new DistanceUtility(); is legal  if you do not define any constructors, Java will generate a default no-argument constructor for you

 our DistanceUtility API exposes only static constants (and methods later on)  its state is constant  there is no benefit in instantiating a DistanceUtility object  a client can access the constants (and methods) without creating a DistanceUtility object double kmPerMi = DistanceUtility.KILOMETRES_PER_MILE;  can prevent instantiation by declaring a private constructor Preventing Instantiation 6

Version 2 (prevent instantiation) 7 public class DistanceUtility { // attributes public static final double KILOMETRES_PER_MILE = ; // constructors // suppress default ctor for non-instantiation private DistanceUtility() {} } [notes 1.2.3]

Version 2.1 (even better) 8 public class DistanceUtility { // attributes public static final double KILOMETRES_PER_MILE = ; // constructors // suppress default ctor for non-instantiation private DistanceUtility() { throw new AssertionError(); } } [notes 1.2.3]

private 9  private attributes, constructors, and methods cannot be accessed by clients  they are not part of the class API  private attributes, constructors, and methods are accessible only inside the scope of the class  a class with only private constructors indicates to clients that they cannot use new to create instances of the class

Utilities 10  in Java, a utility class is a class having only static attributes and static methods  uses:  group related methods on primitive values or arrays  java.lang.Math or java.util.Arrays  group static methods for objects that implement an interface  java.util.Collections  [notes 1.6.1–1.6.3]  group static methods on a final class  more on this when we talk about inheritance

Version 3 (with methods) 11 public class DistanceUtility { public static final double KILOMETRES_PER_MILE = ; private DistanceUtility() {} // methods public static double kilometresToMiles(double km) { double result = km / KILOMETRES_PER_MILE; return result; }

Methods 12 public static double kilometresToMiles(double km)  a method is a member that performs an action  a method has a signature (name + number and types of the parameters) kilometresToMiles(double)  all method signatures in a class must be unique namenumber and types of parameters signature

Methods 13 public static double kilometresToMiles(double km)  a method returns a typed value or void double  use return to indicate the value to be returned public static double kilometresToMiles(double km) { double result = km / KILOMETRES_PER_MILE; return result; }

Parameters 14  sometimes called formal parameters  for a method, the parameter names must be unique  but a parameter can have the same name as an attribute (see [notes 1.3.3])  the scope of a parameter is the body of the method

static Methods 15  a method that is static is a per-class member  client does not need an object to invoke the method  client uses the class name to access the method double miles = DistanceUtility.kilometresToMiles(100.0);  static methods are also called class methods  a static method can only use static attributes of the class [notes 1.2.4], [AJ ]

Invoking Methods 16  a client invokes a method by passing arguments to the method  the types of the arguments must be compatible with the types of parameters in the method signature  the values of the arguments must satisfy the preconditions of the method contract [JBA 2.3.3] double kilometres = 100.0; double miles = 0.0; miles = DistanceUtility.kilometresToMiles(kilometres); arguments 84 kilometres100.0 miles0.0

Pass-by-value with Primitive Types 17  an invoked method runs in its own area of memory that contains storage for its parameters  each parameter is initialized with the value of its corresponding argument 84 kilometres miles 0.0 parameter km gets the value of argument kilometres miles = DistanceUtility.kilometresToMiles(kilometres); public static double kilometresToMiles(double km) 550DistanceUtility. kilometresToMiles km result 100.0

Pass-by-value with Primitive Types 18  the method body runs and the return value is computed  the return value is then copied back to the caller 550DistanceUtility. kilometresToMiles km result value of result gets copied into miles miles = DistanceUtility.kilometresToMiles(kilometres); public static double kilometresToMiles(double km) kilometres miles

Pass-by-value with Primitive Types 19  the argument kilometres and the parameter km have the same value but they are distinct variables  when DistanceUtility.kilometresToMiles() changes the value of km the value of kilometres does not change 550 DistanceUtility. kilometresToMiles km 84 kilometres100.0 miles kilometres does not change miles = DistanceUtility.kilometresToMiles(kilometres); public static double kilometresToMiles(double km) { km /= KILOMETRES_PER_MILE; return km; }

Pass-by-value with Reference Types 20  Java uses pass-by-value for primitive and reference types public class Doubler { // attributes and ctors not shown public static void twice(Rectangle x) { x.setWidth(2 * x.getWidth()); x.setHeight(2 * x.getHeight()); } [notes and 1.3.2]

Pass-by-value with Reference Types 21 r = new Rectangle(3,4); Doubler.twice(r); 64 client r 500 Rectangle object width3 height4 600 Doubler.twice x value of r is a reference to the new Rectangle object parameter x gets the value of argument r (a reference) 6 8 see also [AJ 5.2 (p )]

Exercise for the Student 22  suppose Doubler was incorrectly implemented like so: public class Doubler { // attributes and ctors not shown public static void twice(Rectangle x) { Rectangle y = new Rectangle(2 * x.getWidth(), 2 * x.getHeight()); x = y; }  draw the memory diagram for the previous slide using this version of Doubler

Pass-by-value 23  Java uses pass-by-value for primitive and reference types  an argument of primitive type cannot be changed by a method  an argument of reference type can have its state changed by a method

Testing 24  a unit test tests the smallest testable unit of code  in object-oriented programming unit tests test methods public class KmToMilesTest { public static void main(String[] args) { // 100 km == miles final double KM = 100.0; final double MILES = ; final double TOLERANCE = ; double test = DistanceUtility.kilometresToMiles(KM); if (Math.abs(test - MILES) > TOLERANCE) { System.out.println("test failed"); System.out.print("got " + test + expected " + MILES); } see also [notes 1.2.5]

Version 4 (Javadoc) 1 25 /** * The class DistanceUtility contains constants and * methods to convert between kilometres and miles. * CSE1030Z */ public class DistanceUtility { /** * The number of kilometres in a mile. */ public static final double KILOMETRES_PER_MILE = ;

Version 4 (Javadoc) 2 26 /** * Converts distances in kilometres to miles. * km The distance to convert. If km * is negative then the returned distance is * also negative. Distance in miles. */ public static double kilometresToMiles(double km) { double result = km / KILOMETRES_PER_MILE; return result; }

Javadoc 27  Javadoc processes doc comments that immediately precede a class, attribute, constructor or method declaration  doc comments delimited by /** and */  doc comment written in HTML and made up of two parts 1. a description  first sentence of description gets copied to the summary section  only one description block; can use to create separate paragraphs 2. block tags  @exception ) is non-standard (custom tag used in CSE1030)

Javadoc Guidelines 28  x html x html  [notes 1.5.1, 1.5.2]  precede every exported class, interface, constructor, method, and attribute with a doc comment  for methods the doc comment should describe the contract between the method and the client  preconditions ([notes 1.4], [JBA 2.3.3])  postconditions ([notes 1.4], [JBA 2.3.3])