COMP201 Java Programming

Download Report

Transcript COMP201 Java Programming

COMP201 Java Programming
Topic 3: Classes and Objects
Readings: Chapter 4
Especially “documentation and class design hints”
COMP201 Topic 3 / Slide 2
Outline

An Example: What does a Java class look like

Ingredients of a class: How to write a class





Instance fields
Initialization and constructors
Methods
Class modifiers
Packages: How classes fit together
COMP201 Topic 3 / Slide 3
An Example
class Employee
{ // constructor
public Employee(String n, double s,
int year, int month, int day)
{ name = n;
salary = s;
GregorianCalendar calendar
= new GregorianCalendar(year, month - 1, day);
// GregorianCalendar uses 0 for January
hireDay = calendar.getTime();
}
// methods
public String getName()
{ return name;
}
COMP201 Topic 3 / Slide 4
An Example
public double getSalary()
{ return salary; }
public Date getHireDay()
{ return hireDay;
}
public void raiseSalary(double byPercent)
{ double raise = salary * byPercent / 100;
salary += raise;
}
private String name;
private double salary;
private Date hireDay;
}
COMP201 Topic 3 / Slide 5
An Example
import java.util.*;
public class EmployeeTest
{
public static void main(String[] args)
{
// fill the staff array with three Employee objects
Employee[] staff = new Employee[3];
staff[0] = new Employee("Carl Cracker", 75000,
1987, 12, 15);
staff[1] = new Employee("Harry Hacker", 50000,
1989, 10, 1);
staff[2] = new Employee("Tony Tester", 40000,
1990, 3, 15);
COMP201 Topic 3 / Slide 6
An Example
// raise everyone's salary by 5%
for (int i = 0; i < staff.length; i++)
staff[i].raiseSalary(5);
// print out information about all Employee objects
for (int i = 0; i < staff.length; i++)
{
Employee e = staff[i];
System.out.println("name=" + e.getName()
+ ",salary=" + e.getSalary()
+ ",hireDay=" + e.getHireDay());
}
}
} //EmployeeTest.java
COMP201 Topic 3 / Slide 7
Date and GregorianCalendar

Date: a class belong to the standard Java library. An instance of the Date
class has a state, means a particular point in time, represented by the
number of milliseconds from a fixed point.

GregorianCalendar: expresses dates in the familiar calendar notation.
new GregorianCalendar() //date & time when constructed
//midnight of Chinese New Year eve
GregorianCalendar now=new GregorianCalendar(2002,2, 11)
int month = now.get(Calendar.MONTH);
int day = now.get(Calendar.DAY_OF_WEEK);

Converting between Date and GregorianCalendar
Date time = now.getTime();
now.setTime(time);
COMP201 Topic 3 / Slide 8
Output of the Example
name=Carl Cracker,salary=78750.0,hireDay=Tue Dec
15 00:00:00 GMT+08:00 1987
name=Harry Hacker,salary=52500.0,hireDay=Sun Oct
01 00:00:00 GMT+08:00 1989
name=Tony Tester,salary=42000.0,hireDay=Thu Mar
15 00:00:00 GMT+08:00 1990
COMP201 Topic 3 / Slide 9
Ingredients of a Class

A class is a template or blueprint from which objects are created.
class NameOfClass
{
constructor1 // construction of object
constructor2
…
method1
// behavior of object
method2
…
field1
// state of object
field2
…
}
COMP201 Topic 3 / Slide 10
Instance Fields

Instance fields describe state of object

Plan:

Various types of instance fields

Initialization of instance fields
COMP201 Topic 3 / Slide 11
Instance Fields

Access modifiers:





private: visible only within this class
Default (no modifier): visible in package
protected: visible in package and subclasses
public: visible everywhere
It is never a good idea to have public instance fields because
everyone can modify it. Normally, we want to make fields private. OOP
principle.
COMP201 Topic 3 / Slide 12
Final Instance Fields

Declared with modifier final.

Must be initialized when object is created .
Cannot be modified afterwards,


Example:
class Employee
{ …
private final String name;
}
COMP201 Topic 3 / Slide 13
Static Instance Fields
 Declared
with modifier static.
 It
belongs to class rather than any individual
object.
 Usage: className.staticField
NOT
objectName.staticField

Examples: System.out, System.in
COMP201 Topic 3 / Slide 14
Static Instance Field
class Employee
{public Employee(String n, double s,
int year, int month, int day)
{ name = n;
salary = s;
GregorianCalendar calendar
= new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime()
numOfEmpoyees ++;
}
…
public static int numOfEmployees = 0;
…}
Employee.numOfEmpoyees; // ok
Employee hacker = new Employee(…);
hacker.numOfEmployee;
// wrong
COMP201 Topic 3 / Slide 15
Static Final Instance Fields


Constants:

Declared with static final.

Initialized at declaration and cannot be modified.
Example:
Public class Math
{ …
public static final double PI = 3.141592;
…
}

Notes:


Static fields are rare, static constants are more common.
Although we should avoid public fields as a principle, public
constants are ok.
COMP201 Topic 3 / Slide 16
Initialization of Instance Fields

Several ways:
 Explicit
initialization
 Initialization block
 Default initialization
 Constructors
COMP201 Topic 3 / Slide 17
Initialization of Instance Fields

Explicit initialization: initialization at declaration.
public static int numOfEmployees = 0;
public static final double PI = 3.141592;

Initialization value does not have to be a constant value.
class Employee
{ …
static int assignId()
{ int r = nextId;
nextId++;
return r;
}…
private int id = assignId();
private static int nextId=1;
}
COMP201 Topic 3 / Slide 18
Initialization of Instance Fields

Initialization block:
 Class declaration can contain arbitrary blocks of codes.
 Those blocks are executed when object are being
constructed.
class Employee
{ …
// object initialization block
{ id = nextId;
nextId++;
}
…
private int id;
private static int nextId=1;
}
COMP201 Topic 3 / Slide 19
Initialization of Instance Fields
class Employee
{public Employee(String n, double s,
int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar
= new GregorianCalendar(year, month - 1, day);
// GregorianCalendar uses 0 for January
hireDay = calendar.getTime();
}
new Employee("Harry Hacker",
private String name;
private double salary; 35000, 1989,10,1);
private Date hireDay;
}
COMP201 Topic 3 / Slide 20
Default Initialization
If programmer provides no constructors, Java provides
an a default constructor that set all fields to default
values
– Numeric fields, 0
– Boolean fields, false
– Object variables, null
Note: If a programmer supplies at least one constructor but does
not supply a default constructor, it is illegal to call the default
constructor.
In our example, the following should be wrong if we don’t have the
constructor shown on the previous slide:
New Employee(); // not ok
COMP201 Topic 3 / Slide 21
Initialization



Java initializes instance fields to a default (0, null
for objects, false) if you don’t initialize them
explicitly using a constructor.
If there is no constructor, a default constructor is
invoked to do the initialization.
Unlike in C++, you can initialize instance fields directly
in the class definition.
class Customer{
………
private int nextOrder =1;
}
COMP201 Topic 3 / Slide 22
Constructors
 A class
can have one or more constructors.
 A constructor
–Has the same name as the class
–May take zero, one, or more parameters
–Has no return value
–Always called with the new operator
COMP201 Topic 3 / Slide 23
Default Constructor


Constructors with no parameters.
Written by programmer or supplied automatically by
Java.
public Employee()
{
name = “”;
salary = 0;
hireDay = null;
}
COMP201 Topic 3 / Slide 24
Order of initialization




Default values assigned or properties set to default value
If the first line of the constructor calls another constructor
then that constructor is executed.
All field initializers and initialization blocks are executed,
in the order they occur in the class declaration.
The body of the constructor is executed.
COMP201 Topic 3 / Slide 25
Using this in Constructors
this refers to the current object.
 More meaningful parameter names for constructors
public Employee(String name, double salary, int year,
int month, int day) {
this.name = name;

this.salary = salary;
本
…
}

No copy constructor in Java. To copy objects, use the clone method,
which will be discussed later.
COMP201 Topic 3 / Slide 26
Object Creation and Destruction

Must use new to create an object instance
Employee hacker = new Employee("Harry Hacker",
35000, 1989,10,1);
This is illegal:
Employee number007(“Bond”, 1000, 2002, 2, 7);

No delete operator. Objects are destroyed automatically by garbage
collector

To timely reclaim resources, add a finalize method to your class.
This method is called usually before garbage collect sweep away your
object. But you never know when.

A better way is to add a dispose method to your class and call it
manually in your code.
COMP201 Topic 3 / Slide 27
Methods

Methods are functions that determine what we can do to objects
Parameter (argument) syntax same as in C
Parameters are all passed by value;
But note that identifiers to objects (array, strings, etc.) are actually
references. While the references cannot be modified, contents of
objects might.
Return value can be anything, including an array or an object.

Plan:





Types of methods
 Parameters of methods
 Function overloading
 Access rights of methods
COMP201 Topic 3 / Slide 28
Type of Methods

Accessor methods:
public String getName()
{
return name;
}

Mutator methods:
Public void setSalary(double newSalary)
{
salary = newSalary;
}

Factory methods: generate objects of the same class.
Will discuss later.
COMP201 Topic 3 / Slide 29
Static Methods

Declared with modifier static.

It belongs to class rather than any individual object.
Usage: className.staticMethod() NOT

objectName.staticMethod()

Examples:
– public static void main(String args[])
Because we don’t have any objects at the beginning.
COMP201 Topic 3 / Slide 30
Methods
class Employee
{public Employee(String n, double s,
int year, int month, int day)
{ name = n;
salary = s;
GregorianCalendar calendar
= new GregorianCalendar(year,month - 1, day);
hireDay = calendar.getTime();
numCreated++;
}
…
public static int getNumOfEmployees()
{ return numOfEmpolyees;}
private static int numOfEmployees = 0;
…}
Employee.getNumOfEmployee(); // ok
Harry.getNumOfEmployee(); // not ok
COMP201 Topic 3 / Slide 31
A Diversion/Command-Line arguments
public static void main(String args[])
{
for (int i=0; i<args.length; i++)
System.out.print(args[i]+“ ”);
System.out.print(“\n”);
}
// note that the first element args[0] is not
// the name of the class, but the first
// argument
//CommandLine.java
COMP201 Topic 3 / Slide 32
Parameters

Parameter (argument) syntax same as in C

Parameters are all passed by value;
– A method cannot modify the values of parameter variables.

But note that values of object variables are
actually references (locations) of objects. While
the references cannot be modified, states of
objects might.
COMP201 Topic 3 / Slide 33
Parameters/Pass by Value
Employee a = new Employee(“Alice”, ….);
Employee b = new Employee(“Bob”, ….);
swap(a, b);
….
// a swap function with no effect
void swap(Object x, Object y)
{
Object temp = x;
x = y;
y = temp;
}
//The x and y parameters of the swap method are initialized with
copies of a,b. After swap, x refers to Bob and y to Alice, but
the original variables a and b still refer to the same objects
as they did before the method call. ( ParamTest.java)
COMP201 Topic 3 / Slide 34
Parameters/Pass by Value
// a function that modify objects
void bonus(Employee a, double x)
{
a.raiseSalary(x);//a.salary modified although a is not
}
//ParamTest.java
COMP201 Topic 3 / Slide 35
Function Overloading

Can re-use names for functions with different
parameter types
void sort (int[] array);
void sort (double[] array);

Can have different numbers of arguments
void indexof (char ch);
void indexof (String s, int startPosition);

Cannot overload solely on return type
void sort (int[] array);
boolean sort (int[] array);
// not ok
COMP201 Topic 3 / Slide 36
Resolution of Overloading

Compiler finds best match
– Prefers exact type match over all others
– Finds “closest” approximation
– Only considers widening conversions, not narrowing

Process is called “resolution”
void binky (int i, int j);
void binky (double d, double e);
binky(10, 8) //will use (int, int)
binky(3.5, 4) //will use (double, double)
COMP201 Topic 3 / Slide 37
Access rights of methods


A method can access the public fields and methods of any classes that
are visible to it (see next slide).
A method of a class can access the private fields of any objects of the
same class:
class Employee
{ …
Boolean equals(Employee other)
{
return name.equal( other.name );
}
}
In if (harry.equals( boss) …)
method equals accesses the private field name of both harry and
boss.
COMP201 Topic 3 / Slide 38
Class Modifiers




Default (no modifier): visible in package
public: visible everywhere
private: only for inner classes, visible in the outer class
(more on this later)
Each source file can contain at most one public class,
which must have the same name as the file.
File: EmployeeTest.java
public class EmployeeTest {…}
class Employee {…}
COMP201 Topic 3 / Slide 39
Packages

Classes are grouped into packages.

A program involves multiple packages.

Next:




Finding information about existing packages
Creating your own package
Using packages (to build a program)
Informing Java compiler where packages are located.
COMP201 Topic 3 / Slide 40
Information About Existing Packages

Information about existing packages can be found online
http://java.sun.com/products/jdk/1.3/docs/api/
Linked to course page.

Examples:

java.lang, java,lang.ref, java,lang.reflect
Java.util, java.util.jar, java.util.zip

Packages are organized hierarchically.

COMP201 Topic 3 / Slide 41
Creating Your Own Package

To create a package named foo,




Create a directory with that name: classDir/foo
Add line “package foo;” to the top of all class files of the
package
Place the class files under foo or its subdirectories.
To create a sub-package of foo named bar,




Create a subdirectory named bar: classDir/foo/bar
Add line “package bar;” to the top of all class files of the
package
Place the class files under bar or its subdirectories.
The sub-package is known as “foo.bar”.
COMP201 Topic 3 / Slide 42
Creating Your Own Packages

If a class file has no package specification, it belongs to
the default package located at the current directory.

If a class file under baseDire/foo/bar does not
contain the “package …” line, it belongs to foo.bar
by default.

If you want it to be part of foo, you must add line
“package foo;” to the top.
//PackageTest.java
COMP201 Topic 3 / Slide 43
import Packages

Full name for a class: packageName.className
Java.util.Date today = new Java.util.Date();

Use import so as to to use shorthand reference
import java.util.*;
Differ from “include” directive in
Date today = new Date();
C++. Merely a convenience.

Can import all classes in a package with wildcard
 import java.util.*;
 Makes everything in the java.util package accessible by
shorthand name: Date, Hashtable, etc.
o
Everything in java.lang already available by short name, no
import necessary
COMP201 Topic 3 / Slide 44
Resolving Name Conflict

Both java.util and java.sql contain a Date class
import java.util.*;
import java.sql.*;
Date today; //ERROR--java.util.Date or java.sql.Date?

Solution:
import java.util.*;
import java.sql.*;
import java.util.Date;

What if we need both? Use full name
java.util.Date today = new java.util.Date();
java.sql.Date deadline = new java.sql.Date();
COMP201 Topic 3 / Slide 45
Using Packages

Java compiler has “make” facility built-in,
 It automatically searches for classes used
– Runtime library files (under jre/lib and jre/lib/ext)
– In files under current directory
– In imported packages.

No makefile necessary
COMP201 Topic 3 / Slide 46
Informing Compiler Locations of Packages


Can do from command line, but inconvenient
Set the CLASSPATH environment variable:

On UNIX/Linux: Add a line such as the following to .cshrc
setenv CLASSPATH /home/user/classDir1:/home/user/classDir2:.
– The separator “:” allows you to indicate several base directories where
packages are located.
– The last “.” means the current directory. Must be there.

On Windows 95/98: Add a line such as the following to the
autoexec.bat file
SET CLASSPATH=c:\user\classDir1;\user\classDir2;.
– Now, the separator is “;”.

On Windows NT/2000: Do the above from control panel
COMP201 Topic 3 / Slide 47
Informing Compiler Locations of Packages


Example:
setenv CLASSPATH
/homes/lzhang/DOS/teach/201/code/:/appl/Web
/HomePages/faculty/lzhang/teach/201/codes/s
ervlet/jswdk/lib/servlet.jar:/appl/Web/Home
Pages/faculty/lzhang/teach/201/codes/servle
t/jswdk/webserver.jar:.
jar files: archive files that contain packages. Will discuss
later.