Lecture 1 - Java Re-Visit
Lecture 1 - Java Re-Visit
Java Re-visit
1
Reading materials
Chapter 1: Java review, page 3-64
Cahpter 4: classes and interfaces, page 193-206
Chapter 5: generics, page 270-278
2
Review of Java Fundamentals
Program Structures Useful Java classes
Language Basics User-defined classes
Selection Text input and
statements output
Iteration File input and output
Statements
3
Program Structure
Typical Java program consists of
User written classes
Classes
Data fields
Methods
4
Hello world!
public class Prog {
static public void main(String[] args) {
System.out.println("Hello world!"); // S.o.p. or simply Sop
} //end main
} // end Prog
5
Using command line
arguements
public class Prog {
static public void main(String[] args) {
System.out.println("Hello " + args[0] + ", I am " + args[1] );
} //end main
} // end SimpleSphere
Enter:
java Prog John Ang
Output:
Hello John, I am Ang
6
Packages
Provide a mechanism for grouping related classes
Java assumes all classes in a particular package are
contained in same directory
Java API consists of many predefined packages
import statement
Allows us to use classes contained in packages
Usually we need to
import java.util.*;
import java.io.*;
Package java.lang is imported implicitly
7
References
Java has eight primitive data types
byte, short, int, long, float, double, char, boolean
All non-primitive data types are called reference
types, or class types
e.g. in
String greeting ;
the String variable greeting is a reference variable
All reference variables are pointers initialized with
null (0) if they are not initialized with specific values,
and access through them will cause
NullPointerException . So greeting is a null pointer.
greeting = "Hello"; // greeting now points to "Hello"
8
Aliases
Two variables referencing the same instance of a
class are aliases
e.g. in
9
Classes (1)
Class definition includes
Keyword class
Class body
10
Classes (2)
Each Java class defines a new data type.
A class specifies data (variables or constants) and
methods available for instances of the class. Both
data and methods are called members of the class
class = data + methods
An object in Java is an instance of a class
new operator: to create an object from a class
11
Membership Categories of a class
Public members can be accessed without any restriction through
any object containing the members
Private members can be accessed by methods of the class.
It can be accessed from a sibling object too!
12
Accessing Members of an Object:
Dot (select) operator
Let obj be an object with members data d and function f()
To use obj 's members, the dot operator (or select
operator) is needed:
obj.d // to access the data
obj.f() // to call the function
If the members are static members of a class C, then use
C.d and
C.f()
Example:
Math.sqrt(…)
System.out.println()
13
Methods (1)
Each method should perform one well-defined task
Valued method
Returns a value
Void method
Does not return a value
return; // is valid
14
Methods (2)
Syntax of a method declaration
access-modifier use-modifiers return-type
method-name (list of variables) {
method-body
}
Variables appeared in method header are formal parameters
15
Constructors
A constructor looks like a method. It has the same name as the
class but no return type
A default constructor has no parameter
A constructor is executed when an object is to be created
When a class has multiple constructors
one of them should be properly implemented and called by other
constructors.
If a class has not specified a constructor
it will be given a default constructor by the compiler
To invoke a constructor, use the new operator:
Circle c = new Circle(5);
Circle(4); // invalid, as it cannot be called as a method
16
Accessor, Mutator, and facilitator
Accessor methods
to find out the values of the “private” member variables
Mutator methods
to change the values of the “private” member variables
Facilitator methods
to do some computation without modifying any member
variable
17
class Circle
public class Circle {
private radius;
public Circle() { this (1);} // default constructor
public Circle (int r) { radius = r; } // another constructor
public getRadius() { return radius;}// accessor
public setRadius(int r) {radius = r;}// mutator
public double area() { return …;} // facilitaors
public double perimeter() { return …;} //
}
18
File Input and Output
File
Sequence of components of the same type that
resides in auxiliary storage
Can be large
19
Text Files
Designed for easy communication with people
Flexible and easy to use
End-of-file symbol
Follows the last component in a file
20
A text file with end-of-line and
end-of-file symbols
21
Reading from text files
FileReader and BufferedReader
Open a stream from a file for read,
use class FileReader
This may throw a
FileNotFoundException
Stream is usually embedded within
an instance of class BufferedReader
which buffers characters so as to
provide efficient reading
This class provides text
processing capabilities such as
readLine
22
Reading from text files
BufferedReader input; // Both are null!
String inputLine;
try {
input = new BufferedReader(new FileReader("Ages.dat"));
while ((inputLine = input.readLine()) != null) { // eof?
... // process line of data
}
} // end try
catch (IOException e) {
System.out.println(e);
System.exit(1); // I/O error, the program exits
} // end catch
23
Output to text files
FileWriter and PrintWriter
To output to a text file, need to open an output
stream to the file
Use class FileWriter to open an output stream
For ease of output operation, an output stream is
usually embedded within an instance of class
PrintWriter
That provides methods print and println
24
Output to text files
try {
PrintWriter output = new PrintWriter(new
FileWriter("Results.dat"));
output.println("Results of the survey");
output.println("Number of males: " + numMales);
output.println("Number of females: " + numFemales);
// other code and output appears here...
} // end try
catch (IOException e) {
System.out.println(e);
System.exit(1); // I/O error, the program exits
} // end catch
25
java Cat outfile infile1 infile2 …
public class Cat {
public static void main(String[] args) {
PrintWriter out;
int i;
try {
out = new PrintWriter (new FileWriter (args[0] ));
for (i = 1; i < args.length; ++i) {
Scanner sc = new Scanner(new File( args[i] ));
out.println("\n\t\tcontent of " + args[i] + " :\n");
while (sc.hasNextLine()) {
String line = sc.nextLine();
out.println(line); }
sc.close(); }
out.close(); }
catch (FileNotFoundException e) { … }
catch (IOException e) { … } // end catch
}} 26
Closing and appending a file
Closing a file
Syntax
myStream.close();
Appending to a text file
Syntax
27
Useful Java Classes:
Class String (1)
Declaration examples:
String title; // just a null pointer
String title1 = “Walls and Mirrors”;
Assignment example:
title = “Walls and Mirrors”;
String length example:
title.length();
Referencing a single character
title.charAt(0);
Comparing strings // Should not use s1 == s2
s1.compareTo(s2); // <0, s1 < s2
// =0, s1 == s2
// >0, s1 > s2
28
Useful Java Classes:
Class String (2)
Concatenation example:
String monthName = "December";
int day = 31;
int year = 02;
String date = monthName + " " + day + ", 20" + year;
// date = "December 31, 2002“ //error: yeart will be 202 instead of 2002
Q: What do we get for the following statements?
String date1 = monthName + day + year;
String date2 = monthName + (day + year);
29
Useful Java Classes:
Class StringBuilder
Once a String object is created, it cannot be changed. All methods
modifying a String object return new String objects.
StringBuilder allows a string object to be modified without creating
new string objects.
StringBuilder msg = new StringBuilder(“Rover");
msg.setCharAt(0,'R'); // Rover
msg.append(", roll over!"); // Rover, roll over!
msg.insert(7, "Rover, "); // Rover, Rover, roll over!
msg.delete(0,7); // Rover, roll over! range is [0,7)
msg.replace(7,16, "come here"); // Rover, come here!
String finalMsg = msg.toString();// String from StringBuilder
30
More on Java
Java 2 (JDK 1.5) – using generic
Class Inheritance and Interfaces
Exception handling
31
New features of Java 2
Class Scanner (taught in cs1101)
Auto-boxing/unboxing
supports automatic conversion between
primitive data types and the corresponding
wrapper objects
Enhanced For Loop for traversing collections and
arrays
Definition of classes with Generic Types
32
Scanner class
A scanner breaks input into tokens using a
delimiter pattern, which by default matches with
white space.
33
To read from System.in
Use the following code:
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your height in feet and inches:");
int feet = sc.nextInt();
int inches = sc.nextInt();
The user could type either
62
on one line, or
6 2
on one line, or
6
2
on two lines.
34
To read from a text file
Scanner sc = new Scanner(new File("data.txt"));
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
}
sc.close();
35
What is so good about the
Scanner class?
Data entered from a keyboard are in ASCII code
and they have to be converted to internal format
such as int, float, or double.
If sc is a Scanner object connected to the input
channel , then we can use sc.nextInt() to get the
next integer, sc.nextFloat() to get the next float, etc
with automatic data conversion.
If there are some numbers in a string (i.e., they are
in ASCII), can we use a Scanner object to extract
and convert them?
Yes, we can, if we have a way to turn a string into a
Scanner object.
36
To read from a String?
String input = "red fish blue fish";
Scanner sc = new Scanner(input);
System.out.println(sc.next());
System.out.println(sc.next());
System.out.println(sc.next());
System.out.println(sc.next());
sc.close();
output:
red
fish
blue
fish
37
Extracting information from a string
Scanner sc= new Scanner (“Now 2.14 30”);
String s;
double d;
int x;
s = sc.next();
d = sc.nextDouble();
x = sc.nextInt();
// s == “Now”, d == 2.14, x == 30
39
How to solve Input Ambiguity?
Scanner sc = new Scanner(System.in); // This is for reading
while (sc.hasNextLine()) { // process one line at a time
String line = sc.nextLine();
Scanner scLine = new Scanner(line);// This is for tokenization
int i = 0;
int coef[3];
while (scLine.hasNextInt()) {
coef[i] = scLine.nextInt();
++i; // get coefs
}
// solve the equation
// How do you know whether you are dealing with a
// linear or quadratic equation?
}
40
Specifying delimiters
String input = "red,fish,blue,fish";
Scanner sc = new Scanner(input);
sc.useDelimiter(",");
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
s.close();
output:
red
fish
blue
fish
41
To detect end of file
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
// …
}
System.out.println("End of file encountered");
}
string
45
Auto-boxing / Auto-unboxing
auto-boxing : converting a primitive value to its
corresponding wrapper object
auto-unboxing : converting a wrapper object to
its corresponding primitive value
e.g.
Integer n = 28; // auto-boxing
int x =n; // auto-unboxing
46
Boxing and unboxing example
Scanner sc = new Scanner(System.in);
System.out.print("What is his age? ");
int hisAge = sc.nextInt();
System.out.print("What is her age? ");
Integer herAge = sc.nextInt(); // Boxing?
Integer ageDifference = Math.abs(hisAge – herAge);
// Boxing? unboxing?
System.out.println("He is " + hisAge + ", she is " +
herAge + ": a difference of " + ageDifference + ".");
47
Enhanced for Loop (1)
import java.util.*;
class Test_for_each_loop {
public static void main (String [] args) {
int a [ ] = {2, 2, 3, 4, 5};
// To add all elements of a
int result = 0;
for (int i : a) result += i;
System.out.println ("Result is " + result);
// To print the array
for (int i : a) System.out.println (i);
49
Drawbacks of arrays
The length of an array must be declared when the array
is created, and the length cannot be changed thereafter
If an array is not full, we must keep track of the last
position currently in use
Inserting a new item into an array necessitates pushing
down the elements at and below the insertion point.
Similarly, deleting an element necessitates pulling
elements up to fill the gap.
Is there an alternative?
Note:
For an array a[], its length can be found in a.length.
For an object (such as string) s, its length is found by calling
s.length(), or s.size()
50
Vector
The Vector class implements a growable array of
objects.
Like an array, it contains components that can be
accessed using an integer index.
However, the size of a Vector can grow or shrink as
needed to accommodate adding or removing items
after the Vector has been created.
51
boolean add(E o)
Appends the specified element to the end of this Vector.
void add(int index, E element)
Inserts the specified element at the specified position in this Vector.
int capacity()
Returns the current capacity of this vector.
void clear()
Removes all of the elements from this Vector.
boolean contains(Object elem)
Tests if the specified object is a component in this vector.
E elementAt(int index)
Returns the component at the specified index.
int indexOf(Object elem)
Searches for the first occurence of the given argument
boolean isEmpty()
Tests if this vector has no components.
E remove(int index)
Removes the element at the specified position in this Vector.
boolean remove(Object o)
Removes the first occurrence of the specified element in this Vector
E setElementAt(E obj, int index)
Sets the component at the specified index to be the specified object.
int size()
Returns the number of components in this vector. 52
Using a vector and
an enhanced for loop
import java.util.*;
public class MyVector {
public static void main(String[] args) {
Vector<String> band = new Vector<String>(10);
band.add("Paul");
Program output:
band.add("Pete");
[Paul, Pete, John, George]
band.add("John");
band.add("George"); [Paul, John, George]
System.out.println(band); At index 1: John
band.remove("Pete"); Paul John Ringo George
System.out.println(band); size: 4 capacity: 10
System.out.println("At index 1: " + band.elementAt(1));
band.add(2, "Ringo");
for (String s : band) System.out.print (s + " "); // enhanced for loop
System.out.print ( "size: " + band.size());
System.out.println ( " capacity: " + band.capacity());
}
53
}
How to reuse codes?
We want to re-use code as much as possible
Inheritance is one way to re-use contents of a
class, method, interface, including the type of
the data used.
Another way is to make a class capable of
handling the most general data type – Object
Class Object, the most general class, is the
mother (base class) of all classes
54
When class Object is used
(mainly in old version of java)
The frequent castings needed when class Object is used
is a bit annoying:
class ArrayList { // old version of Java (jdk 1.3)
void add (Object item) { …. }
Object get (int i) { …. }
}
ArrayList myIntList = new ArrayList ();
myIntList.add (new Integer (88));
Integer x = (Integer) (myIntList.get (0));
56
Pair of int
To return an int from a method, simply declare its return type as
int. For example,
int max(int a, int b);
To return a pair of int, we have to return an object of the class
PairOfInt :
class PairOfInt {
int first;
int second;
}
For example,
PairOfInt minAndMax (int [] a)
What if a pair of float, or a pair of double is to be returned? Must
class PairOfFloat or class PairOfDouble be defined?
No, if we use generic.
57
Generic classes
A generic class describes a class in terms of object
type parameters
Usually these parameters are specified as T, E, or
any short symbols in upper case.
These parameters are replaced by actual data
types when declaring an instance of the class.
58
Class OrderedPair<T> (1)
public class OrderedPair <T> { // T can not be primitive data type
private T first, second;
public OrderedPair() {}
public void setPair(T firstItem, T secondItem) {
first = firstItem;
second = secondItem;
}
public void changeOrder() {
T temp = first;
first = second;
second = temp;
}
public String toString() { return "(" + first + ", " + second + ")"; }
} // end OrderedPair
Note:
toString() is a very useful method of a class
59
Class OrderedPair<T> (2)
OrderedPair<String> fruit = new OrderedPair<String> ();
fruit.setPair("apple", "orange");
fruit. changeOrder();
OrderedPair<Integer> xyCoord = new OrderedPair<Integer> ();
// Use object type!
xyCoord.setPair(1,2); // boxing
xyCoord. changeOrder();
60
Class Pair<S, T>
public class Pair <S, T> {
private S first;
private T second;
public Pair(S firstItem, T secondItem) {
first = firstItem;
second = secondItem;
}
public String toString() { return "(" + first + ", " + second + ")"; }
} // end Pair
61
Advantages of using Generics
62
generic array not supported
class genericArray <T> { To overcome this problem, use type
private T[] anArray; casting:
static final int MAX = 50; class genericArray <T> {
genericArray () { private Object [] anArray;
anArray = new T[MAX]; static final int MAX = 50;
} genericArray () {
} anArray = (T[]) new Object [MAX];
Compilation error: }
genericArray.java:6: }
generic array creation
anArray = new T[MAX]; Compiler will generate warning:
^ uncheck type casting error
1 error
63
Generic methods
Just like class and interface, method can also be generic.
public class A { // A is not generic, but the method below is
public static <T> void swap (T a, T b) {
T tmp;
tmp = a;
a = b;
b = tmp;
}
static public void main(String[] args) {
int a = 1;
int b = 2;
swap (a,b);
System.out.println("a:" + a + " b:" + b);
} //end main
} // end class Generic
// output: a:1 b:2 Surprising??? 64
Generic methods involving
comparison (1)
First attempt:
public class A {
public static <T> T max (T a, T b) {
if (a < b) return b;
else return a;
}
}
Failed!
< is only defined for numbers and their wrappers only.
To compare 2 objects obj1 and obj2, we should use
obj1.compareTo(obj2);
65
Generic methods involving
comparison (2)
Second attempt:
public class A {
public static <T> T max (T a, T b) {
if (a.compareTo(b) < 0) return b;
else return a;
}
}
Failed again!
T must have implemented (extended) Comparable<T>
interface in order that compareTo() can be called
through a of type T
66
Generic methods involving
comparison (3)
Final attempt:
public class A {
public static
<T extends Comparable<? super T> >
T max (T a, T b) {
if (a.compareTo(b) < 0) return b;
else return a;
}
static public void main(String[] args) {
System.out.println("max(3,5):" + max(3,5));
} //end main
} // end class Generic
Note:
T extends Comparable<? super T>
means that T must support the compareTo() method which
could have been implemented in any of the super class of T 67
and inherited by T.
Some useful generic java classes
They are in java.util package:
- ArrayList <E>
- Vector <E>
- List <E> // interface
- LinkedList <E>
- Stack <E>
- Queue <E> // interface
68
ArrayList <E>/ Vector<E> (1)
import java.util.*;
class Circle {
private int radius;
public Circle (int r) {radius = r; }
public String toString () { return "C [" + radius + "]";}
}
class TestArrayListAndVector {
public static void main (String [] args) {
ArrayList <Integer> ai = new ArrayList <Integer> ();
ArrayList <Circle> ac = new ArrayList <Circle> ();
Vector <Circle> vc = new Vector <Circle> ();
69
ArrayList <E>/ Vector<E> (2)
for (int i = 1; i <= 5; i++) {
ai.add (i); // auto boxing
ac.add (new Circle (i));
vc.add (new Circle (i));
}
for (int i : ai) System.out.print (i + "\t"); // auto unboxing
System.out.println ();
for (Circle c : ac) System.out.print (c + "\t");
System.out.println ();
for (Circle c : vc) System.out.print (c + "\t");
System.out.println ();
}
}
1 2 3 4 5
C [1] C [2] C [3] C [4] C [5]
70
C [1] C [2] C [3] C [4] C [5]
Outline of Class Inheritance
To learn about:
Super-classes and sub-classes
Abstract classes
71
Class Inheritance
Inheritance: To derive new classes by extending
existing classes
72
Class Inheritance
(in UML notation)
Superclass Subclass
Circle Cylinder
- radius: double - length: double
+ getRadius (): double + getLength(): double
+ setRadius (radius: double): void + setLength(length: double): void
+ findArea(): double + findVolume(): double
73
class CircleWithAccessors
// CircleWithAccessors.java: The circle class with accessor methods
public class CircleWithAccessors {
private double radius;
public CircleWithAccessors() // default constructor
{ this (1.0); }
public CircleWithAccessors(double r) // constructor
{ radius = r; }
public double getRadius() // accessor
{ return radius; }
public void setRadius(double newRadius) // mutator
{ radius = newRadius;}
public double findArea() // facilitator
{ return radius * radius * 3.14159;}
}
74
class Cylinder1 extends
CircleWithAccessors
// Cylinder1.java: Class definition for Cylinder
public class Cylinder1 extends CircleWithAccessors {
private double length;
public Cylinder1() {
this (1.0, 1.0);
}
public Cylinder1(double r, double l) {
super (r); // Call superclass' constructor CircleWithAccessors(r)
length = l;
}
public double getLength() { return length; }
public double findVolume() { return findArea() * length;}
}
75
class TestCylinder
// TestCylinder.java: Use inheritance.
public class TestCylinder {
public static void main(String[] args) {
// Create a Cylinder object and display its properties
Cylinder1 myCylinder = new Cylinder1(5.0, 2.0);
System.out.println("The length is " + myCylinder.getLength());
System.out.println("The radius is " + myCylinder.getRadius());
System.out.println("The volume of the cylinder is " +
myCylinder.findVolume());
System.out.println("The area of the circle is " +
myCylinder.findArea());
}
}
Note: getRadius() and findArea() are inherited
76
Using the Keyword super
The keyword super refers to the superclass of the class
in which super appears. It can be used in two
ways:
1. To call a superclass constructor
2. To call a superclass method.
77
Calling Superclass Constructors
To call a superclass constructor, use
super () or super (parameters)
A subclass’s constructor will always invoke super ()
if super () or super (parameters) is not invoked
explicitly in the constructor.
The statement super () or super (parameters)
must appear as the 1st line of the subclass
constructor if it is called.
78
Example on
calling superclass constructors
C3's default constructor
class C3 {
C2's default constructor
public C3 () { // constructor
C1's constructor
System.out.println ("C3's default constructor");}
}
class C2 extends C3 {
public C2 () { // implicitly call C3's constructor
System.out.println ("C2's default constructor");}
}
public class C1 extends C2 {
public C1 () { // implicitly call C2's constructor
System.out.println ("C1's default constructor");}
public C1 (int n) { // implicitly call C2's constructor
System.out.println ("C1's constructor");}
public static void main (String [] args)
{ new C1 (1); } // Which constructor do we call?
}
79
Superclass default constructor
If a superclass defines constructors other than a
default constructor,
then the subclass cannot use the default
constructor of the superclass as the
superclass does not have one.
class B {
public B (String name) { // non-default constructor
System.out.println (“B’s non-default constructor”);
} // Will the compiler gives B a default constructor?
}
public class A extends B {
// class A cannot be compiled as the default constructor
// of A given by the compiler has a call to the default
// constructor of B which does not exist
} 80
Calling Superclass Methods
The keyword super also can be used to refer to
a method other than the constructor in the
superclass.
For example, in Cylinder1 class, if it has defined
its findArea() method, then to call the findArea()
method in the superclass CircleWithAccessors ,
super is needed:
double findVolume () {
return super.findArea () * length;
}
81
Accessing super-super class attributes
83
Example of method overridding (1)
// Cylinder2.java: New cylinder class that overrides the findArea()
public class Cylinder2 extends CircleWithAccessors {
private double length;
public Cylinder2() {length = 1.0; } // Where is super()?
public Cylinder2(double radius, double l) {
super (radius);
length = l;
}
public double getLength() { return length;}
public double findArea() { // method overridding
return 2 * super.findArea() + 2 * getRadius() * Math.PI * length;
}
public double findVolume() {return super.findArea() * length; }
}
Q: Do we have to specify super.getRadius()?
84
Example of method overridding (2)
// TestOverrideMethod.java: Test the Cylinder class that overrides
// its superclass's methods.
public class TestOverrideMethod {
public static void main(String[] args) {
Cylinder2 myCylinder = new Cylinder2(5.0, 2.0);
System.out.println("The length is " + myCylinder.getLength());
System.out.println("The radius is " + myCylinder.getRadius());
System.out.println("The surface area of the cylinder is "+
myCylinder.findArea());
System.out.println("The volume of the cylinder is "+
myCylinder.findVolume());
}
}
85
Abstract Classes
In the inheritance hierarchy, classes become more
specific and concrete with each new subclass.
86
Abstract methods and
abstract classes
An abstract method is a method declared as abstract,
not implemented, and all derived class must eventually
implement
An abstract class is a class that has at least one
abstract method
public abstract class GeometricObject {
public abstract double findArea();
public abstract double findPerimeter();
public double semiperimeter(){
return findPerimeter ( )/ 2;
}
}
87
Abstract class GeometricObject
// GeometricObject.java: public boolean isFilled(){return filled;}
public abstract class public void setFilled(boolean f) {
GeometricObject { filled = f;
private String color = "white"; }
private boolean filled; public abstract double findArea();
protected GeometricObject() {} public abstract double findPerimeter();
protected GeometricObject }
(String c, boolean f) {
color = c;
filled = f;
}
public String getColor() {
return color;}
public void setColor(String c){
color = c; }
88
Abstract class can implement
an interface as well
public abstract class GeometricObject implements Comparable
<GeometricObject > {
…
public int compareTo (GeometricObject x) {
if (findArea () == x. findArea ())
return 0;
else if (findArea () > x. findArea ())
return 1;
else
return -1;
}
}
89
class Circle extends GeometricObject
92
class Cylinder extends Circle (1)
public class Cylinder extends Circle {
private double length;
public Cylinder() { this(1.0, 1.0);}
public Cylinder(double radius, double length) {
this(radius, "white", false, length);}
public Cylinder(double radius,
String color, boolean filled, double l) {
super(radius, color, filled);
length = l;
}
public double getLength() { return length;}
public void setLength(double l) { length = l;}
93
class Cylinder extends Circle (2)
94
Polymorphism -- intuition
A dog is an animal. A cat is also an animal. To describe
them in classes, both Dog and Cat can be developed as
subclasses of Animal class.
All animals make noise. Given an animal (object), we can
always call animal.makeNoise(). Since different animal
makes different noise, the makeNoise() method in the
Animal class is an abstract method.
As a subclass of Animal, Dog has to implement
makeNoise() to bark, and Cat has to implement
makeNoise() to meow.
When animal.makeNoise() is executed, polymorphism
allows the correct version of makeNoise() to be called so
that barking or meowing can be expected depending on
whether an animal (object) is a dog or a cat.
95
Polymorphism
Polymorphism –many forms (faces) literally.
The ability to perform the operations according to the
identity of an object instantiated from one of the
many related subclasses of a class
For example, a Cylinder, Circle, Rectangle are
subclasses of GeometricObject
Thus a GeometricObject object has three faces. It
may behave as a Cylinder, Circle, or Rectangle
according to the true identity of this object
Polymorphism can be realized through dynamic
binding
96
Dynamic Binding (1)
A method may be defined in a superclass but
overridden in a subclass.
Which implementation of the method is used on a
particular call will be determined dynamically by
the Java Virtual Machine at runtime.
This capability is known as dynamic binding, the
binding of a method to its actual implementation
during runtime.
97
Dynamic Binding (2)
Dynamic binding works as follows:
Suppose an object o is an instance of C1 with C1 a
subclass of C2, C2 a subclass of C3, etc. Cn is the most
general class and C1 is the most specific class.
In Java, Cn is the Object class. If we invoke a method
m() through o, the Java Virtual Machine will search for
this method in C1, C2, …, Cn-1 and Cn until it is found,
and the first found is invoked.
If m() is found in C1, then it is called immediately
without moving up the inheritance hierarchy. This
happens when we execute o.makeNoise() with o being
a Dog object of C1, regarded as a subclass of Animal
class C2
98
Dynamic Binding (3)
Polymorphism allows methods to be used for a
wide range of object arguments.
We may pass an object as an argument of a
method if the class of this object is a subclass of
the class of the parameter
The method invoked through this object is
determined dynamically by the class of the
argument, not by the class of the parameter.
99
Example on Dynamic Binding
public class TestPolymorphism {
public static void main(String[] args) {
GeometricObject geoObject1 = new Circle (5);
GeometricObject geoObject2 = new Rectangle (5, 3);
System.out.println("Do the two objects have the same area? "
+ equalArea(geoObject1, geoObject2));
displayGeometricObject(geoObject1);
displayGeometricObject(geoObject2);
}
static boolean equalArea( GeometricObject o1, GeometricObject o2) {
return o1.findArea() == o2.findArea();}
static void displayGeometricObject( GeometricObject object) {
System.out.println();
System.out.println(object.toString());
System.out.println("The area is " + object.findArea());
System.out.println("The perimeter is " + object.findPerimeter());
}
} 100
Interfaces
The interface in Java consists of public abstract methods and
public static final fields only.
A class is said to implement an interface if it provides definitions
for all of the abstract methods in the interface
Each interface is compiled into a separate bytecode file, just like
a regular class.
We cannot create an instance of an interface, but
We can use an interface as a data type for a variable,
as the result of casting etc.
To define an interface called InterfaceName, use:
modifier interface InterfaceName {
/* Constant declarations */
/* Method signatures */
}
101
Implementing several
interfaces
Sometimes it is necessary to derive a subclass
from several classes, thus inheriting their data
and methods. Java, however, does not allow
multiple inheritance.
The extends keyword allows only one parent
class. With interfaces, we can achieve the effect
close to that of multiple inheritance by
implementing several interfaces.
For example,
public class Vector<E> extends AbstractList<E>
implements List<E>, RandomAccess,
Cloneable, Serializable
Q: What are the methods that are abstract in AbstractList<E>?
102
Interface Comparable<T>
Suppose we want to design a generic method to find the
larger of two objects, we can use the following interface in
java.lang:
// Interface for comparing objects
package java.lang;
public interface Comparable<T> {
public int compareTo (T o);
}
The compareTo method determines the order of “this”
object with the specified object o, and returns -1, 0 or +1
if “this” object is regarded as smaller, equal, or larger than
the specified object o. (Similar to the concepts of <, ==, >
applicable to numbers and their wrappers)
103
Comparable<String>
When T is String, then the interface of interest is
Comparable<String>. Any class that has implemented the
method compareTo(String s) can claim to have implemented
Comparable<String>.
Example:
class A implements Comparable<String> {
public int compareTo(String s) { return 0;}
public static void main (String [] args) {
A a = new A();
System.out.println(a.compareTo(""));
}
}
Note that class A does not have anything to do with String other
than having implemented the method compareTo(String s)
104
Using Interface As Data Type
public class A {
public static Comparable <String> max(String o1, String o2) {
if (o1.compareTo(o2 ) > 0) return o1;
else return o2;
}
public static void main (String [] args) {
String s1 = “abcdef”;
String s2 = “acdef”;
Comparable <String> s3 = max (s1, s2); // s3 supports all methods
// described in the interface Comparable <String>
System.out.println (s3); // dynamic binding to toString() of
// String class is done here
}
}
Note that String class implements Comparable<String> and it is
valid to return a string object as a Comparable<String> object 105
Interfaces vs.
Abstract Classes
data
In an interface, all data are constants (keyword final is omitted)
methods
In an interface, all methods are not implemented
keyword abstract
In an interface, the keyword abstract in the method signature
can be omitted
In an abstract class, it is needed for an abstract method.
Inheritance
A class can implement multiple interfaces
106
Exception
outline
• What Is An Exception?
• Why Is Exception Handling Important?
• Types of Exceptions
• Throwing Exceptions
• Ordinary Exceptions
• Runtime Exceptions
• finally clause -- Forced Execution
• User-defined exception classes
107
Divide by zero
public static void main(String[] args) { As the program does not
int a, b; indicate how to deal with
Scanner sc = new Scanner(System.in); division by zero, the system
System.out.print( "Enter a and b: "); will take over the control
a = sc.nextInt(); and crash the program after
b = sc.nextInt(); the message is printed.
int c = a / b;
System.out.println("c is " + c );
}
Enter a and b: 3 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at DivideByZero.main(DivideByZero.java:10)
108
What is An Exception?
An exception is an event that disrupts the normal
flow of a program. This event is usually described
by an object.
Exception handling is the process of detecting
and responding to an exception
An error is a specific type of exception that a
program is usually unable to handle.
109
Why Is Exception Handling Important?
It provides a means to separate exception-
handling code from normal functioning code.
110
Without exception
Scanner sc = new Scanner (System.in);
System.out.println("Enter number of donuts:");
int donutCount = sc.nextInt();
System.out.println("Enter number of glasses of milk:");
int milkCount = sc.nextInt();
if (milkCount < 1)
System.out.println("No milk! Go buy some!");
else {
double donutPerGlass = donutCount / (double)milkCount;
System.out.println("You have " + donutPerGlass + " donuts for
each glass of milk.");
}
112
Throwing an exception
When an exception is detected by a program, it
can be thrown with a throw statement.
A throw statement can appear anywhere
The code that deals with an exception is said to
catch ( handle, deal with) the exception.
113
Catching an exception
General Syntax for handling an exception:
try { // try block
statement (s); // exceptions might be thrown
} // followed by one or more catch block
catch (ExceptionClass1 identifier) { // a catch block
statement (s); // Do something about the exception
}
catch (ExceptionClass2 identifier) { // another catch block
statement (s); // Do something about the exception
}
…
114
Types of Exceptions
There are 3 types of exceptions:
115
Catching more than one Exceptions
try {
TroubleMaker1 (); // may throw an exception
TroubleMaker2 (); // may throw another exception
…
}
catch (DivideByZeroException e) { // more specific exception
System.out.println (e.getMessage ());
}
catch (AnotherException e) { // another specific exception
System.out.println (e.getMessage ());
}
catch (Exception e) {// general exception considered last
e. printStackTrace();
}
116
Class Exception
When an exception thrown in a program is a
descendant of the class Exception, the program must
have code to handle (check) it, and it is called a
checked exception.
Checked exceptions are ordinary exceptions:
FileNotFoundException
IOException
117
Class RuntimeException
When an exception class is derived from
RuntimeException class, it needs not be caught in a
catch block or specifed in a throw clause of a
method, and it is called an unchecked exception
ArrayIndexOutOfBoundException
NullPointerException
ArithmeticException
NoSuchElementException
IndexOutOfBoundException
ClassCastException
UnsupportedOperationException
119
class Throwable
Throwable is the mother of all exception classes
It is the common super class of Exception and Error
If the most general exception is to be specified, use
Throwable.
120
finally clause -- Forced Execution
To clean up or release some resources (such as closing files or release
some structures to memory pool), a finally clause is provided.
try {
int x = 100;
for (int n = 10; n >= 0; n--) System.out.println (x / n);
return;
}
catch (ArithmeticException e) {System.out.println (e.getMessage ());}
finally { // Always executed even when
// there is a return statement in try block
System.out.println (“Can’t get around me!”);
}
Note: "divide by zero" will throw ArithmeticException
121
Declare the throwing of exceptions
A method must declare which exceptions are thrown in its header if
1. exceptions have been thrown in it
2. exceptions might be thrown by methods it calls and yet it does
not catch them
public void thisIsTrouble () throws anException {
…
throw new anException ();
}
public void thisIsRealTrouble () throws Exception1, Exception2{
method1(); // may throw Exception1
method2(); // may throw Exception2
} // Exception1 and Exception2 are not handled by this method
122
User defined Exceptions (1)
class DivideByZeroException extends Exception {
public DivideByZeroException () {
super ("Divide By Zero Exception!");
}
public DivideByZeroException (String msg) {
super (msg);
}
}
123
User defined Exceptions (2)
public class DivideByZero1 { When b = 0,
public static void main(String[] args) { the print out:
int a, b, c = 100; my own Exception
Scanner sc = new Scanner(System.in); c is 100
System.out.println( "Enter a and b: ");
a = sc.nextInt();
b = sc.nextInt();
try { c = divide(a , b); }
catch (DivideByZeroException e) {System.out.println
(e.getMessage ()); }
System.out.println("c is " + c );
}
static int divide (int a, int b) throws DivideByZeroException{
if (b == 0) throw new DivideByZeroException("my own Exception");
return a/b;}
} 124
Assertions
An assertion is a statement of truth.
For example, in
double sqrt(double x) {
assert x>0;
…
}
when sqrt() is called with a negative x, the program will terminate:
Exception in thread "main" java.lang.AssertionError
If we use assert x>0 : x;
then the error message printed when sqrt(-5.1) is executed will be
Exception in thread "main" java.lang.AssertionError: -5.1
Assert statements will be executed only when they are enabled:
java –ea MyProgram
125