Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Review of Week 1
What is a Class? What is an Object?
What is a class?
A blue-print or a definition for a kind of object.
(Exception: some classes provide only services)
What is an object?
An instance of a class -- a "thing" in a program that
has:
1. behavior (methods)
2. state (attributes)
3. identity (it exists and is unique)
Creating Objects
What is the statement to create a new Purse with
capacity 20 coins?
{
Purse purse = new Purse( 20 ) ;
Object versus Object Reference
purse is an object reference. purse is not an object!
Purse purse;
purse = null
// how much money in the Purse?
int balance = purse.getBalance( );
NullPointerException
You can Change a Reference
What amount is printed?
What happened to purse #1
Purse purse = new Purse( 20 );
// Purse #1
purse.insert( new Coin(10) );
purse = new Purse( 30 );
// Purse #2
System.out.println("You have "+
purse.getBalance( ) + " Baht");
Compiling and Running Java
What is the command to compile a Java source file
named "Hello.java" ?
Command> javac Hello.java
What is the command to execute a Java class file
named "Hello.class" ?
Command> java Hello
Immutable Object
Can you change a Coin object after you create it?
Coin
- value : int
<<constructor>>
+Coin( value : int )
+getValue( ) : int
+toString( ) : String
Import
What does "import java.util.Scanner" do?
1. include the Scanner class in compiled program.
2. include Scanner source code in this class
3. add java.util.Scanner to CLASSPATH
4. add java.util.Scanner to current name space
Import
A. The "import" command is processed by (choose one):
1. Java compiler
2. Java interpreter (Java VM)
3. Java program editor
B. "import X.Y" is like what statement in C# ?
1.
using X.Y;
2.
namespace X.Y;
3.
include "X.Y";
What am I?
Identify as one of:
package
class
object
primitive type
attribute of object
instance method
static method
class constant
interface
String
long
Long
java.lang.String
"hello class"
"hello class".length( )
java.lang
java.lang.System
System.out
System.out.println("hello")
java.lang.Math
Math.sqrt( )
Math.PI
java.lang.Comparable
Object
java.util.Arrays.sort(array)
Locations
What is "java.lang" ?
Name some classes in "java.lang"
(True/False) You should always
"import java.lang.*" so your program can use the
classes in java.lang.
3 Packages You Should Know
java.lang
java.io
java.util
Core Java language classes
String
Object
Math
System
Input and Output classes
InputStream
OutputStream
Utility and date/time classes
Scanner
Date
Calendar
ArrayList
Arrays
More import
(True/False)
The command "import java.util.*" does...
includes the code for all classes in java.util into your
program
adds all classes in java.util to the name space
makes the compiled program larger
Ordering
Order these statements 1, 2, 3, 4, ...
__5_
__4_
__7_
__1_
__6_
__3_
private String name; // attribute
public class Cat {
}
package packagename;
public Cat(String name) { ... }
/**
* javadoc comment for this class
* @author Your Name
*/
__2_ import java.util.Scanner;
Ordering of Contents
In Sun's Java coding standard, what is the order of these
statements (1, 2, 3, ...).
__5_ public Cat(String name, Date birthday) {..}
__7_ public String getName() { return name; }
__6_ /** return the cat's name */
__4_ private String name; attribute
__3_ private static final char SOUND = 'meow';
__1_ import java.util.Scanner;
__2_ public class Cat {
class constant
No Ambiguity Allowed
If there are 2 or more classes with the same name in
the list of imports, the compiler issues an error.
No error if you exactly specify the class name on the
import command.
import java.util.*;
ambiguous (not clear)
import java.sql.*;
import java.util.Date; // specify the Date class
public class Test {
Date today = new Date( );
...etc...
}
Constructors
What is the purpose (job) of a constructor?
Initialize the state (attributes) of a new object.
public Coin( int avalue ) {
this.value = avalue; // initialize value of a coin
}
Can you write a class with no constructors?
YES - Java will automatically provide a default constructor
Can a class have more than one constructor? How?
How to Write Constructor
Constructors, again
Can a constructor call super and call another constructor?
// calling superclass constructor
public Student( String name, String id, String phone ) {
super( name, phone );
this.id = id;
can we do this statement first?
}
// calling our other constructor
public Student( String name, String id ) {
this( name, id, "" );
}
// can we do both?
public Student( String name, String id ) {
super( name, id );
this( name, id, "" );
}
Constructors (2)
The Fraction class has multiple constructors:
Fraction half = new Fraction(1, 2); // = 1/2
Fraction ten = new Fraction( 10 ); // = 10/1
If both constructors perform similar actions, eliminate
duplicate code: let one constructor invoke the other.
public class Fraction {
/** construct a new Fraction = num/denom */
public Fraction( long num, long denom ) {
/* do the real work here */
}
/** constructor makes fraction from an int. */
public Fraction( long num ) {
this( numerator, 1L ); // call other constr.
}
Constructors (3)
What is wrong here?
public class Fraction {
/** construct a new Fraction object */
public Fraction( long num, long denom ) {
/* do the real work here */
...
}
/** constructor makes fraction from a double */
public Fraction(double x) {
if ( Double.isNaN(x) ) this( 0L, 0L );
else if ( Double.isInfinite(x) )
this( 1L, 0L );
else ...
}
Constructor (4)
If a class has a constructor and an initialization block,
which one is used when you use "new Fraction(...)" ?
public class Fraction {
/** initialization block */
{
System.out.println("Run init block.");
}
/** construct a new Fraction object */
public static Fraction( long num, long denom ) {
System.out.println("Run constructor...");
/* do the real work here */
}
public static void main(String[] args) {
Fraction half = new Fraction(1,2);
The "."
What does "." mean? ...as in:
System.out.println( );
Math.PI;
java.util.Scanner;
obj.toString( );
Answer: "." is the scope resolution operator.
"obj.toString()" means "the toString() object
belonging to obj".
What symbol does C++ use for Java's "." ?
Answer: C++ uses :: e.g., as obj::toString();
Review of Lab
Coin Purse Problem
A class should have just one purpose.
All the class's methods are related to that
purpose.
Coin
-value
Purse
getValue( )
-capacity
insert( )
PurseUI
withdraw( )
+mainDialog( )
getBalance( )
+insertDialog( )
+withdrawDialog( )
Design of Classes
Design objects (classes) to resemble things in
the real world.
Immutable Object
Can you change a Coin?
Coin
-value
+Coin(value)
getValue( )
The Three Noble Truths of O-O
Encapsulation: an object contains both data and the
methods that operate on the data. It may expose some
of these to the outside and hide others.
This design separates the public interface from the
implementation, and enforces data integrity.
Inheritance: one class can inherit attributes and
methods from another class.
Polymorphism: the operation performed by a named
method can depend on context. In particular, it can
depend on the type of object it is applied to.
Example: The Three Noble Truths
Give an example of polymorphism.
Number x;
// x is a reference to a Number object
x = new BigDecimal( Math.PI );
// BigDecimal is a subclass of Number, so
// this is OK.
System.out.println("x = "+ x.toString );
// calls the toString() method of BigDecimal
x = new Fraction( 2, 33 );
// Fraction is also a subclass of Number
System.out.println("x = "+ x.toString );
// calls the toString() method of Fraction
More Review Questions
Arrays (1)
How do you declare x to reference an array of double?
double [ ] x;
How do you create an array of 100 double and assign x
to reference it?
x = new double[100];
How do you define an array reference y and set y to
reference the same array as x?
double [ ] y = x;
What is the index of the last element of x?
99
Does the statement "y[1] = 10" change x[1]?
yes. y refers to the same array as x
Arrays (2)
What attribute or method returns the size of an array?
length as in x.length
Is "length" an attribute or a method?
attribute. In contrast, for a
String s, s.length() is a method.
Using length, set "last" equal to the last element of x.
double last = x[x.length - 1];
Is x an object or primitive data type? What about x[1]?
x is an object, x[1] is a double
From the questions above, what fact tells you that x
must be an object, not a primitive?
primitive data types don't have attributes
Arrays (3)
How would create a new array z and copy x to z?
double [] z = new double[x.length];
// arraycopy( src, src_start, dest, dest_start, count)
System.arraycopy(x, 0, z, 0, x.length);
How would you copy x to z using a loop?
for(int k=0; k<x.length; k++) z[k] = x[k];
What does the statement "z = x" do?
make z to refer to the same array as x.
The old storage allocated to z is lost!
What is the meaning of this statement?
String [] fruit = { "Apple", "Orange", "Grape" };
create a new array of length 3 and
assign values to the array elements
Arrays (4)
What is wrong with these statements?
String s = "Arrays are very useful";
String [] words = new String [4];
words = s.split("\\s+"); // split at whitespace
The "words = new String[4]" is useless!
The third line will set words to a new
array (returned by split), so the old
array is discarded.
A better way to write this is:
String s = "Arrays are very useful";
String [] words = s.split("\\s+");
Arrays (5)
What is the value of dates[1] after this statement?
Date [] dates = new Date[10];
null. This line only creates an array of
Date references. It doesn't create any Date
objects.
How do you create Date objects for this array?
for(int k=0; k < dates.length; k++)
dates[k] = new Date( );
What is the value of score[1] after this statement?
int [] score = new int[10];
0
"int" is a primitive data type, so the array elements
contain the data values.
Arrays (6)
Can you change the size of an array after you create it?
For example:
double [] score = new double[10];
int k = 0;
// read scores into an array
while( input.hasNextDouble() && k < score.length )
score[k++] = input.nextDouble();
if ( input.hasNextDouble() ) {
// oops! we need a bigger array
score = new double[20]; // (1)
}
// now read more data...
while( ... ) score[k++] = input.nextDouble();
You can't change the size of an array.
Statement (1) discards the old array!
Arrays (7)
How can you read data and save in an array if you don't
know how much data there will be?
Use an ArrayList After reading the data, convert it to an
array of exactly the size of the actual data. (CJ, page 180).
import java.util.ArrayList;
...
ArrayList<double> arr = new ArrayList<double>( );
// read scores into an array
while( input.hasNextDouble() ) {
double ascore = input.nextDouble();
arr.add ( ascore );
}
// now convert to an array
double [] score = new double[ arr.size() ];
score = arr.toArray( score );
String, Double, Integer, ...
After creating a String object, can you change the
String object?
No. Strings are immutable.
The String class doesn't contain any "set", "append",
"insert", "clear", "delete" or other methods to modify a
string object.
What about String s = "hello"; s = s + " world";
Doesn't that change the String s?
No. "+" creates a new string.
Can you change the value of a Double, Integer, etc.?
No. These objects are also immutable.
immutable: cannot be changed.
String Processing (1)
Why is this loop inefficient?
String text; // text read from the input
Scanner input = new Scanner(System.in);
while ( input.hasNext( ) ) {
String word = input.next( );
text = text + " " + word; // (1)
}
Each time (1) appends a word, it must copy the entire
String (text) to a new string! The old String is discarded.
How could you make this more efficient?
String Processing (2)
How could you make this more efficient?
Use a StringBuffer or StringBuilder object.
You can append strings to a StringBuilder (faster) or
StringBuffer (thread-safe). When you are finished,
convert the object to a String!
StringBuilder buf = new StringBuilder();
Scanner input = new Scanner(System.in);
while ( input.hasNext( ) ) {
String word = input.next( );
buf.append(' ');
append is polymorphic
buf.append(word);
}
String text = buf.toString( );
String Processing (3)
Is it worth the effort to use write extra code to use
StringBuilder?
See my example program: TestStringBuilder.java
It reads a file word-by-word and appends each word to
a String or StringBuilder, as in the previous slides.
For a 40KB file from the Java tutorial, I recorded these
times:
read and append to a String:
6.60 seconds
read and append to StringBuilder:
0.03 seconds
read and append to StringBuffer:
0.03 seconds
For StringBuffer and StringBuilder, these times include
converting the result into a String object!
Immutable Objects
What does it mean for an object to be immutable?
Does this class define immutable objects?
public class Appointment {
No mutator methods!
private Date date;
private String description;
public Appointment( Date when, String what ) {
date = when;
description = what;
}
public Date getDate( ) { return date; }
public String getDescription { return description; }
}
Immutable Objects (2)
It is mutable because Date is mutable. (See Horstmann
for example.)
To fix it, always copy the mutable Date object:
public class Appointment {
private Date date;
private String description;
public Appointment( Date when, String what ) {
date = (Date) when.clone();
description = what;
}
public Date getDate( ) { return (Date)date.clone(); }
public String getDescription { return description; }
}
A Mutable Object
A Date object is mutable. The Date class provides
methods such as setYear(int), setMonth(int), and
setDate(int) to change the year, month, or day.
Date millenia = new Date( 101, // = year - 1900
Calendar.JANUARY, // = month
1 );
// = day
System.out.println(millenia);
// prints "January 1, 2001"
millenia.setYear(99); // change year to 1999
millenia.setMonth(Calendar.MARCH);
millenia.setDate(15);
System.out.println(millenia);
// prints "March 15, 1999"
Encapsulation
How can a class enforce encapsulation of attributes
and still give the other classes ability to read an
attribute's value?
Make the attributes private and provide
an accessor method
Give an example.
class Person {
private String name;
private Date birthday;
public Person(String name, Date birthday)
{
/* set the attributes */ }
// accessor method for name
public String getName() {
return name;
}
Encapsulation and Mutability
A Date object is mutable. The Date class has methods
such as setYear(int), setMonth(int), and setDate(int).
Does this getBirthday() method break encapsulation of
the birthday object?
class Person {
private String name;
private Date birthday;
public Person(String name, Date birthday)
{
/* set the attributes */ }
// accessor method for birthday
public Date getBirthday() {
return birthday;
}
Encapsulation and Mutability (2)
Why? Give an example.
Person you = new Person("a name", new Date(..) );
Date bd = you.getBirthday( );
bd.setYear( 99 ); // change the year to 1900 + 99
How would you fix this problem?
For mutable objects, return a copy of the object.
class Person {
...
// accessor method for birthday
public Date getBirthday() {
return new Date( birthday );
}
For more info, see Core Java chapter 4.
Encapsulation and Mutability (3)
Does this getName() method break encapsulation of
the name object?
class Person {
private String name;
private Date birthday;
public Person(String name, Date birthday)
{
/* set the attributes */ }
// accessor method for name
public String getName() {
return name;
}
No. String objects are immutable, so the caller cannot
use the return value to change the name attribute.
Encapsulation and Accessor Methods
For primitive data types and immutable objects, it is
safe for an accessor method to return the value:
class BankAccount {
private long balance; // account balance
/** return the account balance */
public long getBalance() {
return balance;
// this is safe
}
For mutable objects, an accessor should return a copy:
class Person {
/** return the person's birthday */
public Date getBirthday() {
return new Date( birthday );
}