Transcript ppt
Review : abstract
• abstract method
– a method without implementation
• abstract class
– an “incomplete” class
– force concrete subclasses to implement
abstract methods (if any)
– cannot be instantiated
1
The Student Class Hierarchy
class Student
{
:
public String getGrade()
{
return “ERROR”;
}
}
class PassFailStudent extends Student
{
:
public String getGrade()
{
return (average > 70) ? “pass” : “fail”;
}
}
class LetterGradeStudent extends Student
{
:
public String getGrade()
{
if (average > 90) return “A”;
else if (average > 70) return “B”;
else if (average > 40) return “C”;
else return “D”;
}
}
2
Using Student Class
Student students[] = new Student[numOfStudents];
// create students
:
if (enrolledAsPassFail)
students[i] = new PassFailStudent(..);
else
students[i] = new LetterGradeStudent(..);
students
LetterGradeStudent
PassFailStudent
PassFailStudent
// prints the name and final grade of all students
for (int i = 0; i < numOfStudents;i++)
System.out.println(
students[i].getName() + “\t” +
students[i].getGrade());
3
Abstract Student Class
abstract class Student
{
:
public abstract String getGrade();
}
class PassFailStudent extends Student
{
:
public String getGrade()
{
return (average > 70) ? “pass” : “fail”;
}
}
class LetterGradeStudent extends Student
{
:
public String getGrade()
{
if (average > 90) return “A”;
else if (average > 70) return “B”;
else if (average > 40) return “C”;
else return “D”;
}
}
4
Interface
• “Pure” abstract class
• Must contain only constant members
and abstract methods
• Members are public final static by
default
• Methods are public abstract by
default
5
Implements
• an interface does not contain any
implementation
• a class provides implementations
• We say : a class implements an
interface
6
interface And implements
interface Hero {
boolean NEVER_DIES = true;
void swim();
void fight();
void jump();
};
class Jedi implements Hero {
public void fight()
{
// swing light saber
}
public void swim() { ... }
public void jump() { ... }
}
class WesternHero implements Hero {
public void fight()
{
// punch
}
public void swim() { ... }
public void jump() { ... }
}
7
More interface Examples
interface NumericSet {
void add(Number n);
void remove(Number n);
void union(NumericSet n);
void intersect(NumbericSet n);
boolean isEmpty();
boolean contains(Number n);
int size();
}
interface Printable
{
void print();
}
8
More implements Examples
class ArraySet implements NumericSet, Printable
{
public void add(Number n)
{ ... }
public void remove(Number n)
{ ... }
public void union(NumericSet n)
{ ... }
public void intersect(NumbericSet n)
{ ... }
public boolean isEmpty()
{ ... }
public boolean contains(Number n)
{ ... }
public int size()
{ ... }
public void print()
{ ... }
}
9
Differences
• a class can
implement more
than one interfaces
• A implements B =
“A has the
behaviors of B”
• a class can only
extend one other
class
• A extends B =
“A is a kind of B”
10
Extending Interface
• We can extend an interface
• interface A extends B : B is
called superinterface
• We can override methods in
superinterface
• We can overload methods in
superinterface
11
Extending interface
interface FlyingHero extends Hero
{
void fly();
}
interface RoboticHero extends Hero
{
void fight(Weapon w);
void swim() throws RustException;
}
interface SortedSet extends NumericSet
{
boolean isSorted();
void sort();
Number first();
Number last();
}
interface DoubleClickable extends Clickable
{
void doubleClicked();
}
12
Try it out yourself 1
• can we declare a class without abstract
methods as “abstract” ?
abstract class A {
int f()
{
return 1;
}
}
13
Try it out yourself 2
• must we implement all abstract methods from
the interface ?
interface I {
int f();
int g();
}
class A implements I {
int f() { returns 1; }
}
14
Try it out yourself 3
• can a class implement two interfaces with
methods of the same name?
interface I1 { int f(); }
interface I2 { int f(); }
interface I3 { double f(); }
class A implements I1, I2 {
int f() { return 1; }
}
class B implements I1, I3 {
int f() { return 1; }
double f() { return 1.0; }
}
15
Bugs
• Programming Errors
• First bug
– A moth stuck in a Harvard Mark II
mainframe in 1947.
16
Bugs are bad
• 1990 – AT&T long distance service
failed for 9 hours and was traced to a
single faulty line of code
• 1991 – Scud missile killed 28 soldiers
because a bug caused the Patriot
defense system to be off by 0.34
seconds
• 2000 – Y2K
17
Today’s Lecture
• How to prevent bugs ?
– Understand the problem
– Understand Java
– Follow good programming practices
• How to find bugs ?
– Testing
• How to kill bugs ?
18
Program Development
Design
Implement
Testing
19
Program Design : Classes
Student
double averageGrade
int grades[6]
double weight[6]
calcAverageGrade()
getAverageGrade()
LetterGradeStudent
printGrade()
PassFailStudent
printGrade()
Course
double averageGrade
double max
double min
double sum
int numOfStudent
Student students[]
calcAverageGrade()
getAverageGrade()
20
Program Design : Pseudocode
Average grade for students
for ( i = 0 .. 6)
average += grade[i]*weight[i]
return average
Average Grade for course
for each student
sum += student’s weight average
return sum/number of students;
Get input
get number of students
for i = 1 .. number of students
get name
get enrollment status
get all six grades
if enroll as pass fail then
create a PassFailStudent
else
create a LetterGradeStudent
21
Program Design : Data Flow
pass/fail ?
name
6 grades
create a student
final grade
get final grade
Student obj
calc student’s
average grade
average grade
22
Program Design : Control Flow
i=0
i == # of
students ?
get name
get status
get grades
increment i
23
Good Program vs. Bad Program
• Easy to Read
–
–
–
–
Good Comments
Meaningful Names
Properly Indented
Blank Lines
• Well-Designed
– Cover all cases
– Anticipate Changes
– Facilitate Reuse
24
Very Bad Program
// A program that reads some inputs and outputs some
stuffs
class P2Q3 {
public static void main(String X[]) {
int temp = 0, temp2 = 0, s = 0, c=0, M = 0, X[];
TokenReader tr = new TokenReader();
System.out.println(“number:”);
int N=tr.ReadInt();
X = new int[N];N = tr.ReadInt();
while (N!=0){s+=N;if (N>M)
M=N;X[temp] = N;
temp++;
System.out.println(“number”);N=tr.ReadInt();
temp2++;}
System.out.println(s + “ “ + temp2 + “ “ + temp);
temp2 = temp1 = 0;
while (temp2 < X.length) System.out.println(X[temp1])
temp2++; temp1++;}}
25
Better Program
class P2Q3 {
public static void main(String X[]) {
// sum – total of values entered so far
// max – maximum of values entered so far
// count – number of values entered
int sum = 0, count = 0, max = Integer.MAX_VALUE;
TokenReader tr = new TokenReader();
System.out.println(“Enter number :”);
int input = tr.ReadInt();
// keep reading until user enters 0
while (input != 0){
sum += input;
// compare current input with maximum so far.
// maximum so far if input is larger.
if ( input < max ) {
max = input;
count++;
}
update
System.out.println(“Enter number :”);
input = tr.ReadInt();
}
}
}
26
Good Design
•
•
•
•
Anticipate Changes
Reusable
Encapsulation
Think “LEGO”
27
Bad Histogram Program
public static void main(String args[])
{
TokenReader in = new TokenReader();
int histogram = new int[10];
for (int i = 0; i < 10; i++) {
histogram[i] = 0;
}
int input = in.readInt();
while (input != 0) {
if (input > 1 && input <= 10) {
histogram[0]++;
} else if (input > 10 && input <= 20) {
histogram[1]++;
} else if (...
:
:
// smarter implementation
// int n = (input – 1)/10;
// histogram[n]++;
28
What if ..
• create histogram for data between 1 .. 200 ?
• tally data for smaller intervals ?
1 – 5 | **
6 – 10 | *****
11 – 15 | *
:
:
196 – 200 | ***
• draw a histogram for average grade ?
29
Good Histogram Program
class Histogram {
int numOfBuckets, bucketSize, buckets[];
public Histogram(int numOfBuckets, int bucketSize) {
this.numOfBuckets = numOfBuckets;
this.bucketSize = bucketSize;
buckets = new int[numOfBucket];
for (int j = 0; j < buckets.length; j++)
buckets[j] = 0;
}
public void addData(int data) {
buckets[(data-1)/bucketSize]++;
}
public void print() {
for (int j = 0; j < numOfBucket; j++) {
System.out.println((j*bucketSize+ 1)+
“-” + ((j+1)*bucketSize)));
for (int k = 0; k < buckets[j]; k++)
System.out.print(“*”);
Sysmte.out.println();
}
}
}
30
Bug Preventions
• code reuse
– fewer lines of code to write, fewer bugs
• anticipate changes
– fewer lines of code to change,
fewer bugs
• encapsulation
– bugs are confined to one place, easier to
detect and fix.
31
Good Programs
• Easy to read
– blank lines
– indentation
– comments
– meaningful names
• Easy to read, easy to spot bugs !
32
Finding Bugs
• Wrong attitude :
“My program works ! I am done.”
• Did you test it with all possible inputs ?
– negative numbers ?
– zero ?
• Did you test all possible paths of
execution ?
33
Component Testing
• Another motivation for encapsulations !
• Test each component separately
• Make sure they worked before using
them
34
Debugging Techniques :
Think “high-level”
1. scan from left to right
2. swap two adjacent elements if
they are out of order
3. repeat until everything is in
order
35
Debugging Techniques :
Printout
•
•
•
•
•
Print out your code
Spread it on a large table
Walkthrough your code
Draw diagrams
Make notes
36
Debugging Techniques :
Explain it to Someone Else
• Old Chinese Proverb :
“Onlookers see most of the game;
Players see very little”
37
Debugging Techniques :
System.err.println
• Let you inspect the intermediate value
of variables
53
34
10
82
72
2147483647
2147483647
2147483647
2147483647
2147483647
0
0
0
0
0
• Can you guess what is wrong now ?
38
Using System.err.println
class P2Q3 {
public static void main(String X[]) {
:
:
// keep reading until user enters 0
while (input != 0){
sum += input;
// compare current input with maximum so
// far. update maximum so far if input
// is larger.
if ( input < max ) {
max = input;
count++;
}
System.err.println(input + “ “ + max + “ “
+ count);
System.out.println(“Enter number :”);
input = tr.ReadInt();
}
}
}
39
Debugging Techniques :
assert
• a method to make sure that your
invariants are true.
void assert(boolean condition, String errorMessage)
{
if (!condition)
throw new Error(errorMessage);
}
40
class Histogram {
Using assert
int numOfBuckets;
int bucketSize;
int buckets[];
:
:
public void addData(int data)
{
assert(data >= 0 && data < numOfBuckets*bucketSize,
“data” + data + “is out of range.”);
buckets[(data-1)/bucketSize]++;
}
:
:
}
41
Debugging Techniques :
assert
• The Error exception will cause the
stack trace to be printed.
java.lang.Error: data 364 is out of range
at java.lang.Throwable.<init>
at java.lang.Error.<init>
at Histogram.assert
at Histogram.addData
at P2Q4.createHistogram
at P2Q4.main
42
Debugging Techniques :
Debugger
breakpoint
pause execution
step
incremental execution
continue
resume execution
watch
stop if value of a
variable changes
call stack
variables
list currently active
frames
inspect value of
variables
43
Summary
• Bug Prevention
– understand the problem and language
– design before sit in front of computer
– design for change/reuse
• Bug Discovery
– test all flow of controls
– test small components separately before
using them
44
Summary
• Bug Termination
– re-think your algorithm from a higher-level
– manually trace through your program
– explain your program to others
– System.err.println
– assert
– use a debugger
45