Download Review of Java and OOP

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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
Model for Programming
Real World
Objects
Results
Problem Space
Programmer’s
Representation
of the Problem
Solution Space
Execution/
Interpretation
of the Results
Software
Objects
Addition of new
Solution Space Objects
©SoftMoore Consulting
Slide 2
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 3
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 4
Primitive Data Types
• Integer Types
– int
– long
•
Floating Point Types
– float
•
•
– short
– byte
– double
Type char
Type boolean
©SoftMoore Consulting
Slide 5
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'
'\t'
'\r'
'\b'
'\''
'\"'
'\\'
©SoftMoore Consulting
newline
horizontal tab
carriage return
backspace
apostrophe (single quote)
double quote
backslash
\u000a
\u0009
\u000d
\u0008
\u0027
\u0022
\u005c
Slide 6
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 7
Object Variables and Reference Types
• Example
public class PurchaseOrder
{
…
}
PurchaseOrder order = new PurchaseOrder();
•
The variable order is a reference to the object created
by new – order is not the object itself.
order
reference to
the object
©SoftMoore Consulting
the
PurchaseOrder
object
the object
Slide 8
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 9
Method Example:
Greatest Common Divisor
public static int gcd(int a, int b)
{
int a1, b1, temp;
a1 = (a > 0) ? a : -a;
b1 = (b > 0) ? b : -b;
// a1 = abs(a);
// b1 = abs(b)
while (b1 != 0)
{
temp = a1;
a1 = b1;
b1 = temp % b1;
}
return a1;
}
©SoftMoore Consulting
Slide 10
Variable Parameters
(a.k.a. “Varargs”)
• Motivation: To allow methods to have a variable number
of parameters
•
Example – printf() method introduced in Java 5
System.out.printf("%s %3d", name, age);
• Prior to Java 5 you had to use an array to simulate this
functionality.
©SoftMoore Consulting
Slide 11
Using Variable Parameters
• Syntax
public PrintStream printf(String format, Object... args)
•
•
Ellipsis (...) is part of the syntax
Parameter args has type Object[]
©SoftMoore Consulting
Slide 12
The March of Progress
(Cay Horstmann)
• 1980: C
printf("%10.2f", x);
• 1988: C++
cout << setw(10) << setprecision(2) << showpoint << x;
• 1996: Java
java.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: Java
System.out.printf("%10.2f", x);
©SoftMoore Consulting
Slide 13
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 14
Package
• Collection of classes
• Namespace control; e.g.,
public class Test extends java.awt.Frame { ... }
or
import 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 15
Example: Packages
• Customer.java:
package com.softmoore.sales;
public class Customer {...}
class Credit {...}
// public access
// package access
• Display.java:
package com.softmoore.ui;
import com.softmoore.sales.*;
public class Display
{
Customer c = new Customer();
Credit cr = new Credit();
}
©SoftMoore Consulting
// o.k.
// *** ERROR ***
Slide 16
Dynamic Loading
• Java has no explicit link phase
• Imagine a program made up of nothing but DLLs
• Class definitions are loaded on demand
CLASSPATH is searched for file T.class
©SoftMoore Consulting
Slide 17
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.
“Classes should be immutable unless there is a very
good reason to make them mutable” – Joshua Bloch
©SoftMoore Consulting
Slide 18
Wrapper Classes
• Each Java primitive type has an equivalent class type
called a “wrapper” class.
– Integer
– Float
– Character
•
–
–
–
Byte
Double
…
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.
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.
•
Examples
String
String
String
String
String
•
s0
s1
s2
s3
s4
=
=
=
=
=
new String("Hello");
"Hello";
// short-hand notation
"world";
s1 + ", " + s2;
// "Hello, world"
"j" + s1.substring(1, 5);
// "jello"
Prefer method equals() when comparing strings.
©SoftMoore Consulting
Slide 20
The StringBuffer Class
• Defined in java.lang.StringBuffer
• Provides methods for splicing together characters and
substrings
•
•
Provides various insert/append methods
•
Example
Class StringBuffer is designed to be thread-safe, and
all public methods in StringBuffer are synchronized.
StringBuffer b = new StringBuffer("HelloWorld");
b.insert(5, ", ");
b.append(".");
©SoftMoore Consulting
Slide 21
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 22
Default Constructor
• A default constructor is one that has no arguments
• Example
public class X
{
public X() { … }
…
}
…
X x1 = new X();
©SoftMoore Consulting
Slide 23
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.
•
Example
public class X
{
public X() { … }
public X(X x) { … }
…
};
X x1 = new X();
X x2 = new X(x1);
©SoftMoore Consulting
// default constructor
// copy constructor
// calls default constructor
// calls copy constructor
Slide 24
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
• Example
public class Fraction
{
public Fraction(int n) { … }
…
}
Fraction f1 = new Fraction(5);
// converts integer 5 to Fraction 5/1
©SoftMoore Consulting
Slide 25
General Constructor
• A general constructor is one that does not fit any of the
other special categories. (none of the above)
•
Example
public 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 26
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.
©SoftMoore Consulting
Slide 27