27
Appendix A.1: Review of Java and Object-Oriented Programming: Part 1 “There does not now, nor will there ever, exist a programming language in which it is the least bit hard to write bad programs.” – L. Flon

Appendix A.1: Review of Java and Object-Oriented Programming: Part 1 “There does not now, nor will there ever, exist a programming language in which it

Embed Size (px)

Citation preview

Appendix A.1: Review of Java andObject-Oriented Programming: Part 1

“There does not now, nor will there ever, exist a programming language in which it is the least bit hard to write bad programs.”

– L. Flon

©SoftMoore Consulting Slide 2

Model for Programming

SoftwareObjects

Programmer’sRepresentationof the Problem

Results

Execution/Interpretationof the Results

Real WorldObjects

Problem Space

Solution Space

Addition of newSolution Space Objects

©SoftMoore Consulting Slide 3

File Structure

• Each public Java class requires its own source file.

• Source file– base name equals class name– extension is “.java”

• Object (class) file– contains java bytecode (architecture neutral)– base name equals class name– extension is “.class”– directory structure parallels package structure

©SoftMoore Consulting Slide 4

The Class Path

• CLASSPATH– environment variable specifying where the JVM should look for

user-defined classes– list of directories, JAR files, and ZIP files– location of system classes is appended to the end of the list

• Class path list entry separators– “:” (colon) for Unix– “;” (semicolon) for Windows

• Example.;C:\java\classes;C:\xerces-1_4_4\xerces.jar

©SoftMoore Consulting Slide 5

Primitive Data Types

• Integer Types– int – short– long – byte

• Floating Point Types– float – double

• Type char

• Type boolean

©SoftMoore Consulting Slide 6

The char Type

• Uses Unicode UTF-16 encoding– 16 bit code units (usually code unit = character)– supplementary characters encoded in two code units– can be expressed as hexadecimal values \u0000 to \uffff

• Alternate escape sequences for special characters– '\n' newline \u000a– '\t' horizontal tab \u0009– '\r' carriage return \u000d– '\b' backspace \u0008– '\'' apostrophe (single quote) \u0027– '\"' double quote \u0022– '\\' backslash \u005c

©SoftMoore Consulting Slide 7

Overloaded Method Names

• Method names can be overloaded provided that each signature (number and types of arguments) is unique.String substring(int beginIndex)String substring(int beginIndex, int endIndex)

• From a user point of view, each method provides the same kind of service even though each is implemented in a different way. It makes a program easier to understand.

• The method's return type is not used in resolving references to overloaded methods.

©SoftMoore Consulting Slide 8

Object Variables and Reference Types

• Examplepublic class PurchaseOrder { … }

PurchaseOrder order = new PurchaseOrder();

• The variable order is a reference to the object created by new – order is not the object itself.

thePurchaseOrder

objectthe object

reference tothe object

order

©SoftMoore Consulting Slide 9

Method Arguments

• All arguments to Java methods are passed by value (copy in). Changing the formal argument does not change the actual argument.

• Java passes only references to objects as method arguments, not the objects themselves. Those references are passed by value.

©SoftMoore Consulting Slide 10

Method Example:Greatest Common Divisor

public static int gcd(int a, int b) { int a1, b1, temp;

a1 = (a > 0) ? a : -a; // a1 = abs(a); b1 = (b > 0) ? b : -b; // b1 = abs(b)

while (b1 != 0) { temp = a1; a1 = b1; b1 = temp % b1; } return a1; }

©SoftMoore Consulting Slide 11

Variable Parameters(a.k.a. “Varargs”)

• Motivation: To allow methods to have a variable number of parameters

• Example – printf() method introduced in Java 5System.out.printf("%s %3d", name, age);

• Prior to Java 5 you had to use an array to simulate this functionality.

©SoftMoore Consulting Slide 12

Using Variable Parameters

• Syntaxpublic PrintStream printf(String format, Object... args)

• Ellipsis (...) is part of the syntax

• Parameter args has type Object[]

©SoftMoore Consulting Slide 13

The March of Progress(Cay Horstmann)

• 1980: Cprintf("%10.2f", x);

• 1988: C++cout << setw(10) << setprecision(2) << showpoint << x;

• 1996: Javajava.text.NumberFormat formatter = java.text.NumberFormat.getNumberInstance();formatter.setMinimumFractionDigits(2);formatter.setMaximumFractionDigits(2);String s = formatter.format(x);for (int i = s.length(); i < 10; i++) System.out.print(' ');System.out.print(s);

• 2004: JavaSystem.out.printf("%10.2f", x);

©SoftMoore Consulting Slide 14

Access Control

• public– part of the public interface of the class– visible to any client of the class

• protected– not part of the public interface of the class– visible to any subclass and any class within same package– essentially public to subclasses and classes in the same

package, and private to the rest of the program

• package (no explicit modifier) – visible only to classes within same package

• private– visible only to enclosing class

©SoftMoore Consulting Slide 15

Package

• Collection of classes

• Namespace control; e.g.,public class Test extends java.awt.Frame { ... }

orimport java.awt.Frame;…public class Test extends Frame { … }

• Supports data hiding– public classes are visible to code outside of package– classes with no access modifier are not visible outside the

package

©SoftMoore Consulting Slide 16

Example: Packages

• Customer.java:package com.softmoore.sales;

public class Customer {...} // public accessclass Credit {...} // package access

• Display.java:package com.softmoore.ui;

import com.softmoore.sales.*;

public class Display { Customer c = new Customer(); // o.k. Credit cr = new Credit(); // *** ERROR *** }

©SoftMoore Consulting Slide 17

Dynamic Loading

• Java has no explicit link phase

• Imagine a program made up of nothing but DLLs

• Class definitions are loaded on demandCLASSPATH is searched for file T.class

Immutable Class

• A class is said to be immutable if its instances cannot be modified after construction.

• Guidelines for making a class immutable– Don’t provide methods that modify the object’s state.– Ensure that the class can’t be extended (e.g., make it final).– Make all fields private and final.

• Examples in Java– String – Wrapper classes – BigInteger

• Immutable objects are simple and inherently thread-safe.

©SoftMoore Consulting Slide 18

“Classes should be immutable unless there is a verygood reason to make them mutable” – Joshua Bloch

Wrapper Classes

• Each Java primitive type has an equivalent class type called a “wrapper” class.– Integer – Byte– Float – Double– Character – …

• The wrapper classes contain– public constants that provide attributes of the primitive type,

such as MAX_VALUE and SIZE.– methods for converting to other types, such as String or int

• All wrapper class names begin with a capital letter.

• The wrapper classes are immutable.

©SoftMoore Consulting Slide 20

Strings

• Functionality is provided by standard class java.lang.String (not a primitive type).

• Java strings are immutable – constant length and content. Use class java.lang.StringBuffer or class java.lang.StringBuilder for mutable strings.

• ExamplesString s0 = new String("Hello");String s1 = "Hello"; // short-hand notationString s2 = "world";String s3 = s1 + ", " + s2; // "Hello, world"String s4 = "j" + s1.substring(1, 5); // "jello"

• Prefer method equals() when comparing strings.

©SoftMoore Consulting Slide 21

The StringBuffer Class

• Defined in java.lang.StringBuffer

• Provides methods for splicing together characters and substrings

• Provides various insert/append methods

• Class StringBuffer is designed to be thread-safe, and all public methods in StringBuffer are synchronized.

• ExampleStringBuffer b = new StringBuffer("HelloWorld");b.insert(5, ", ");b.append(".");

©SoftMoore Consulting Slide 22

The StringBuilder Class

• Defined in java.lang.StringBuilder

• Provides an API compatible with StringBuffer, but with no guarantee of synchronization.

• Can be used as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case).

• Recommendation: Use StringBuilder in preference to StringBuffer since it will be faster under most implementations.

©SoftMoore Consulting Slide 23

Default Constructor

• A default constructor is one that has no arguments

• Examplepublic class X { public X() { … } … }…

X x1 = new X();

©SoftMoore Consulting Slide 24

Copy Constructor

• A copy constructor is used to initialize a newly created object with an existing object of the same class.

• A copy constructor has a single argument that is a reference to an object of the same class as the constructor.

• Examplepublic class X { public X() { … } // default constructor public X(X x) { … } // copy constructor … };

X x1 = new X(); // calls default constructorX x2 = new X(x1); // calls copy constructor

©SoftMoore Consulting Slide 25

Conversion Constructor

• A constructor that creates an object of one class and initializes it with the value of an object of a different class is sometimes referred to as a conversion constructor (converts from one class to another).

• A conversion constructor has exactly one argument

• Examplepublic class Fraction { public Fraction(int n) { … } … }

Fraction f1 = new Fraction(5);// converts integer 5 to Fraction 5/1

©SoftMoore Consulting Slide 26

General Constructor

• A general constructor is one that does not fit any of the other special categories. (none of the above)

• Examplepublic class Date { public Date(int year, int month, int day) { … } … }

Date today = new Date(1993, 1, 3);

• The constructor for class Date is not a default constructor, a copy constructor, or a conversion constructor.

©SoftMoore Consulting Slide 27

Information Hiding with Java

• Fields are usually declared to be private.

• Access to private fields is usually restricted to an explicitly declared list of public methods.

• Debugging benefit – all access to data is localized; any illegal value must be caused by a method.

• Maintenance benefit – prevents dependencies on the underlying representation details; changes do not affect user programs.

• Information hiding is enforced by the language.