COMP201 Java Programming Topic 3: Classes and Objects Readings: Chapter 4
COMP201 Java Programming
Topic 3: Classes and Objects
Readings: Chapter 4
COMP201 Topic 3 / Slide 2
Objective
Objective: Shows how to write and use classes
COMP201 Topic 3 / Slide 3
Using Predefined ClassesDate
Class Date: its objects describe points in time, such as 7/2/2005, 13:00:00 . GMT
To construct a Date Object: new Date(); You can also pass the object to a method:
System.out.println(new Date()); String s = new Date().toString();
Or store it to a variable: Date birthday = new Date(); Objects and object variables are different.
Date deadline;// deadline is not an object and doesn’t refer to an object yet.
if you set: deadline = birthday; // both variables refer to the same object.
COMP201 Topic 3 / Slide 4
Using Predefined Classes GregorianCalendar
GregorianCalendar: expresses dates in the familiar calendar notation. Constructors: new GregorianCalendar();
//Create a object that represents the date and time at which the object was constructed.
new GregorianCalendar(2005,1,14); //construct a object for the //midnight on a specified date
OR new GregorianCalendar(2005,Calendar.February, 7 13,59,59); Mutator and Accessor Methods:
GregorianCalendar now = new GregorianCalendar();
int month = now.get(Calendar.Month);
int weekday = now.get(Calendar.DAY_OF_WEEK);
now.set(Calendar.YEAR, 2006);
now.set(Calendar.MONTH, Calendar.APRIL);
now.set(Calendar.DAY_OF_MONTH, 1);
now.add(Calendar.MONTH,3); //move now by 3 months
COMP201 Topic 3 / Slide 5
Convertion between Date and GregorianCalendar
If you know the year, month, and day, and you want to make a Date object with those setting. Because the Date class knows nothing about calendars, first construct a GregorianCalendar object and then call the getTime to obtain a Date :
GregorianCalendar Holiday = new GregorianCalendar(year, month,day);
Date highTime = Holiday .getTime();
You can also set a GregorianCalendar from a Date
Holiday.setTime(highTime); // to set Calendar
COMP201 Topic 3 / Slide 6
Using Predefined ClassesAn Example
We capture the current day and month by calling the get method:GregorianCalendar d = new GregorianCalendar();int today = d.get(Calendar.DAY_OF_WEEK);int month = d.get(Calendar.MONTH);
Set d to the first of the month and get the weekday of that dated.set(Calendar.DAY_OF_MONTH,1);int weekday = d.get(Calendar.DAY_OF_WEEK);
Advance d to the next day:d.add(Calendar.DAY_OF_MONTH,1);
//CalendarTest.java
COMP201 Topic 3 / Slide 7
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
。。。} // See EmployeeTest.java
COMP201 Topic 3 / Slide 8
Outline
Ingredients of a class Instance fields Initialization and constructors Methods Class modifiers
Packages: How classes fit together
COMP201 Topic 3 / Slide 9
Instance Fields
class Employee{ ... private String name; private double salary; private Date hireDay; //java.util.Date }
Various types of fields Classification according to data type
– A field can be of any primitive type or an object of any class
Classification according to accessibility– public, default, protected, private
Classification according to host– static vs non-static
COMP201 Topic 3 / Slide 10
Instance Fields
Access modifiers: private: visible only within this class
class Employee
{ ...
public void raiseSalary(double byPercent)
{ double raise = salary * byPercent / 100;
salary += raise; }
private double salary;
} Default (no modifier): visible in package protected: visible in package and subclasses
COMP201 Topic 3 / Slide 11
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.class Employee
{ ...
public double getSalary() // accessor method
{ return salary; }
// mutator method
public void raiseSalary(double byPercent)
{ double raise = salary * byPercent / 100;
salary += raise; }
private double salary; // private field
}
Instance Fields
COMP201 Topic 3 / Slide 12
static Instance Fields Static fields belong to class, not object
class Employee //StaticTest.java{ ... public void setId() { id = nextID; nextID++; } private int id; private static int nextID =1; }
Usage: className.staticField NOT objectName.staticField although the later works also.– Employee.nextID, harry.NextID, jack.NextID
COMP201 Topic 3 / Slide 13
What if the static in front of nextID is removed?class Employee{ ... public void setId() { id = nextID; nextID++;} private int id; private int nextID = 1; } Employee[] staff = new Employee[3];staff[0] = new Employee("Tom", 40000);staff[1] = new Employee("Dick", 60000);staff[2] = new Employee("Harry", 65000);
for (Employee e : staff) {e.setId();}
//They all get have id 1.
static Instance Fields
COMP201 Topic 3 / Slide 14
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;
…
} //Called with Math.PI Notes:
Static fields are rare, static constants are more common. Although we should avoid public fields as a principle, public constants
are ok.– Examples: System.out, System.in
COMP201 Topic 3 / Slide 15
Outline
Ingredients of a class Instance fields Initialization and constructors Methods Class modifiers
Packages: How classes fit together
COMP201 Topic 3 / Slide 16
Initialization of Instance Fields
Several ways:
1. Explicit initialization
2. Initialization block
3. Constructors
COMP201 Topic 3 / Slide 17
Explicit initialization: initialization at declaration.private double salary = 0.0;private String name = “”;
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;
}
Initialization of Instance Fields
COMP201 Topic 3 / Slide 18
Initialization block: Class declaration can contain arbitrary blocks of codes.class Employee{ … // object initialization block { id = nextId; nextId++;}…private int id;private static int nextId=1;
}
Initialization of Instance Fields
COMP201 Topic 3 / Slide 19
Initialization by constructorsclass 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(); }
private String name;private double salary;private Date hireDay;
}
Initialization of Instance Fields
COMP201 Topic 3 / Slide 20
What happens when a constructor is called
All data fields initialized to their default value (0, false, null)
Field initializers and initialization blocks are executed
Body of the constructor is executed– Note that a constructor might call another constructor at line 1.
Initialization of Instance Fields
COMP201 Topic 3 / Slide 21
Default constructor: Constructor with no parameters
class Employee
{ ...
public Employee()
{
name =“”;
salary = 0;
}
}
Initialization of Instance Fields
COMP201 Topic 3 / Slide 22
If a programmer provides no constructors, Java provides 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 have only the constructor shown on slide 19, then
New Employee(); // not ok
Initialization of Instance Fields
COMP201 Topic 3 / Slide 23
Constructors Constructors define initial state of objectsclass 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 JanuaryhireDay = calendar.getTime();
}private String name; private double salary;private Date hireDay;
}Employee hacker = new Employee("Harry Hacker",35000, 1989,10,1);
COMP201 Topic 3 / Slide 24
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–Almost always public, although can be others–Always called with the new operator
Constructors
COMP201 Topic 3 / Slide 25
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;
… } Can also be used in other methods public void setName( String name)
{ this.name = name; }
No copy constructor in Java. To copy objects, use the clone method, which will be discussed later.
Using this in Constructors
COMP201 Topic 3 / Slide 26
Calling another constructor Can call another constructor at line 1:
class Employee{ public Employee(String name, double salary){...}
public Employee(double salary) {
this(“Employee #” + nextID, salary ); nextID++; }}
Write common construction code only once
COMP201 Topic 3 / Slide 27
Object Creation
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);
COMP201 Topic 3 / Slide 28
No delete operator. Objects are destroyed automatically by garbage collector
Periodically garbage collector destroy objects not referenced. To force garbage collection, call System.gc();
To timely reclaim non-memory resources (IO connection), 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.
Object Destruction
COMP201 Topic 3 / Slide 29
Outline
Ingredients of a class Instance fields Initialization and constructors Methods Class modifiers
Packages: How classes fit together
COMP201 Topic 3 / Slide 30
Methods
Three key characteristics of objects Identity State
– Values of fields Behavior
– What can we do with them?
Methods determine behavior of objects
COMP201 Topic 3 / Slide 31
class Employee{ public String getName() {...} public double getSalary() {...}
public Date getHireDay() {...}
public void raiseSalary(double byPercent) {...}}
Methods
COMP201 Topic 3 / Slide 32
Methods
Plan: Types of methods
Parameters of methods (pass by value)
Function overloading
COMP201 Topic 3 / Slide 33
Methods
Types of methods Classification according to functionality
– Accessor, mutator, factory
Classification according to accessibility– public, protected, default, private
Classification according to the host– static vs non-static
COMP201 Topic 3 / Slide 34
Types of Methods
Accessor methods:
public String getName()
{
return name;
} Mutator methods:
Public void setSalary(double newSalary)
{
salary = newSalary;
}
COMP201 Topic 3 / Slide 35
Types of Methods Factory methods. The NumberFormat class uses factory methods that
yield formatter objects for various styles. Produce objects
NumberFormat.getNumberInstance() // for numbers
NumberFormat.getCurrencyInstance()//currency values
NumberFormat.getPercentInstance()//percentage value
Why useful? (We already have constructors) More flexibility in name
– Constructors must have the same name as class. But sometimes other names make sense.
Factory methods can generate object of subclass, but constructors cannot.
COMP201 Topic 3 / Slide 36
Simple Input/Output
For Example:
double x = 10000.0 / 3.0;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(4);
nf.setMinimumIntegerDigits(6);
System.out.println(nf.format(x));//003,333.3333
COMP201 Topic 3 / Slide 37
Accessibility of Methods public: visible everywhere protected: visible in package and in subclasses Default (no modifier): visible in package private: visible only inside class (more on this later)
A method can access fields and methods that are visible to it. public method and fields of any class protected fields and methods of superclasses and classes in the
same package Fields and methods without modifiers (default) of classes in the
same packages private fields and methods of the same class.
COMP201 Topic 3 / Slide 38
Accessibility of Methods
A method can access the private fields of all objects of its class
class Employee
{ ...
public boolean equals(Employee another)
{
retun name.equals(another.name);
}
private String name;
}
COMP201 Topic 3 / Slide 39
Public method and private field Bad idea for a public method to return a private object
class Employee
{
public Date getHireDay() { return hireDay;}
private String name;
private double salary;
private Date hireDay;
}
Other classes can get the object and modify, although it is supposed to be private to Employee.
Better solution:
public Date getHireDay() { return hireDay.clone();}
COMP201 Topic 3 / Slide 40
Static Methods Declared with modifier static. It belongs to class rather than any individual object. Sometimes called
class method. Usage: className.staticMethod() NOT
objectName.staticMethod()class Employee{ public static int getNumOfEmployees() { return numOfEmpolyees; }private static int numOfEmployees = 0;
… }Employee.getNumOfEmployee(); // okHarry.getNumOfEmployee(); // not this one
COMP201 Topic 3 / Slide 41
Static methods Explicit and implicit parameters:
class Employee{ public void raiseSalary(double byPercent)
{...}}Explicit parameters: byPercentImplicit parameters: this object
Static methods do not have the implicit parameterpublic class Math{ public static double pow(double x, double y) {...}
}Math.pow(2, 3);
COMP201 Topic 3 / Slide 42
Static Methods
The main method
class EmployeeTest
{ public static void main(String[] args)
{}
}
is always static because when it is called, there is no objects yet.
COMP201 Topic 3 / Slide 43
Static Methods A static method cannot access non-static fields
class Employee{ public static int getNumOfEmployees() { return id; // does not compile
// id == this.id } private static int numOfEmployees = 0; private int id = 0; }
COMP201 Topic 3 / Slide 44
Parameters of Method
Parameter (argument) syntax same as in C
Parameters are all passed by value, not by reference Value of parameter copied in function call
public static void doubleValue( double x){ x = 2 * x; }
double A = 1.0;
doubleValue( A );
// A is still 1.0
1.0
2.0
A=
x=
COMP201 Topic 3 / Slide 45
Parameters of Method When parameters are object references Parameter values, i.e. object references are copied
public void swap( Employee x, Employee y)
{ Employee tmp = x; x=y; y=tmp;
}
Employee A = new Employee(“Alice”,..
Employee B = new Employee(“Bob”,..
Swap(A, B)
B=
x=
Alice
y=
Bob
A=
COMP201 Topic 3 / Slide 46
// a function that modify content of object,
// but not object reference
void bonus(Employee A, double x)
{
A.raiseSalary(x);//a.salary modified although a is not
}
//ParamTest.java
Parameters of Method
salary
A=
COMP201 Topic 3 / Slide 47
Command-Line argumentsParameters of the main Method
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 48
Function Overloading
Can re-use names for functions with different parameter typesvoid sort (int[] array);void sort (double[] array);
Can have different numbers of argumentsvoid indexof (char ch);void indexof (String s, int startPosition);
Cannot overload solely on return typevoid sort (int[] array);boolean sort (int[] array); // not ok
COMP201 Topic 3 / Slide 49
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 50
Outline
Ingredients of a class Instance fields Initialization and constructors Methods Class modifiers
Packages: How classes fit together
COMP201 Topic 3 / Slide 51
Class Modifiers
public: visible everywherepublic class EmployeeTest { ...
}
Default (no modifier): visible in packageclass Employee { ...
}
private: only for inner classes, visible in the outer class (more on this later)
public class Tree { ...
private class TreeNode{...}
}
COMP201 Topic 3 / Slide 52
Outline
Ingredients of a class Instance fields Initialization and constructors Methods Class modifiers
Packages: How classes fit together
COMP201 Topic 3 / Slide 53
Packages
Plan What are packages Creating packages Using packages
COMP201 Topic 3 / Slide 54
Packages A package consists of a collection of classes and
interfaces
Information about packages in JSDK 1.5.0 can be found http://java.sun.com/j2se/1.5.0/docs/api/index.html
Example: Package java.lang consists of the following classes Boolean Byte Character Class ClassLoader Compiler
Double Float Integer Long Math Number Object SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread …
COMP201 Topic 3 / Slide 55
Packages Packages are convenient for organizing your work Guarantee uniqueness of class names
Complete name of class: package name + class name Avoids name conflict. Example
– java.sql.Date– java.util.Date
Packages are organized hierarchically, just like nested subdirectory on your computer. Example
– java.security – java.security.acl java.security.cert java.security.interfaces
java.security.spec For java compiler, however, java.security and java.security.acl
are just two packages, having nothing to do with each other.
COMP201 Topic 3 / Slide 56
Creating Packages To add to class to a package, say foo
Begin the class with the line
package foo; This way we can add as many classes to foo as we wish
Where should we keep the class in the foo package? In a directory name foo :
– .../ foo /{first.class, second.class, ...}
Sub packages and subdirectories must match All classes of foo.bar must be placed under .../ foo/bar/ All classes of foo.bar.util must be under .../ foo/bar/util/
COMP201 Topic 3 / Slide 57
Creating Packages
Classes that do not begin with “package ...” belongs to the default package: The package located at the current directory,
which has no name
Consider a class under .../foo/bar/– If it starts with “package foo.bar ”, it
belongs to the package “foo.bar”– Else it belong to the default package
COMP201 Topic 3 / Slide 58
Using Packages Use full name for a class: packageName.className
java.util.Date today = new java.util.Date();
Use import so as to use shorthand reference. It is merely a convenience differ from “include” directive in C++.
import java.util.*;Date today = new Date();
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 59
Using packages Resolving Name Conflict
Both java.util and java.sql contain a Date classimport 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 namejava.util.Date today = new java.util.Date();java.sql.Date deadline = new java.sql.Date();
COMP201 Topic 3 / Slide 60
Static Imports
The import statement can even import static methods and fields, not just classes. For example, if you add: Import static java.lang.System.*;
Then you can output by out.println(“Good bye cruel world”);
More useful, you can use a static import for the Math class, and use mathematical functions in a more natural way.
For example,
sqrt(pow(x,2) + pow(y,2));
COMP201 Topic 3 / Slide 61
Using packages Informing java compiler and JVM location of packages Set the class path environment variable:
– On UNIX/Linux: Add a line such as the following to .cshrcsetenv CLASSPATH /home/user/classDir1:/home/user/classDir2:.
– The separator “:” allows you to indicate several base directories where packages are located.
– Java compiler and JVM will search for packages under both of the following two directories
/home/user/classDir1/ /home/user/classDir2/
– The last “.” means the current directory. Must be there.
COMP201 Topic 3 / Slide 62
Using Packages
Set the CLASSPATH environment variable:
– 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/XP: Do the above from control panel
COMP201 Topic 3 / Slide 63
Example:
setenv CLASSPATH /homes/lzhang/DOS/teach/201/code/:/appl/Web/HomePages/faculty/lzhang/teach/201/codes/servlet/jswdk/lib/servlet.jar:/appl/Web/HomePages/faculty/lzhang/teach/201/codes/servlet/jswdk/webserver.jar:.
jar files: archive files that contain packages. Will discuss later.
Using Packages