49
Debugging Polymorphism and Interface Applet Hands on Computing with Java

Debugging Polymorphism and Interface Applet Hands on Computing with Java

Embed Size (px)

Citation preview

Page 1: Debugging Polymorphism and Interface Applet Hands on Computing with Java

DebuggingPolymorphism and Interface

AppletHands on Computing with Java

Page 2: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Topics

• Debugging techniques

• Advanced OO: Polymorphism

• Abstraction through Interface

• Java Applet

Page 3: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Debugging – a process of finding and reducing/fixing bugs (errors or mistakes) in a computer program.

Types of errors• Compilation Errors

– Program cannot be compiled successfully

• Runtime or Logical Errors– Program is compiled successfully but runs incorrectly

or crashes

Page 4: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Outline• Compilation Errors

– Typical Causes of Compilation Errors– Strategy for locating and fixing compilation errors

• Runtime/Logical Errors– Typical Causes of Runtime or Logical Errors– Strategy for locating and fixing logical errors

• Debugging programs with IDE (NetBeans)

• Interpreting Stack Trace of an Exception• Adding codes to help detecting bugs

Page 5: Debugging Polymorphism and Interface Applet Hands on Computing with Java

• Misspelled names– e.g.: Mixed up lowercase/uppercase letters

• Mismatched parentheses or double quotes – i.e.: { } [ ] ( ) "

• Omitting punctuation symbols– e.g: ; : ,

• Not closing a multi-line comment /* ... */

• Improper use of APIs– e.g.: int x = Math.sqrt("1.23");

Typical Causes of Compilation Errors

Page 6: Debugging Polymorphism and Interface Applet Hands on Computing with Java

/********************************************/ A program that yields compilation errors./*********************************************/class DebugDemo1 { public static void main(String args[]) { if (args.length > 0) { System.out.println("Hello, "); System.out.println(args[0] + "!");} } else System.out.println("Hello, you!"); }}

123456789101112

Hello.java:9: illegal start of type } else ^Hello.java:10: <identifier> expected System.out.println("Hello, you!"); ^Hello.java:12: 'class' or 'interface' expected}^Hello.java:13: 'class' or 'interface' expected^4 errors

Where's the bug?

Page 7: Debugging Polymorphism and Interface Applet Hands on Computing with Java

• Fact: Many of the errors listed by the compilers are caused by the errors that appear before them.

• What should you do?– Locate and fix the first error listed by the compiler and

recompile your program (and repeat the process as long as you need to).

There are so many compilation errors!Which error should I fix first?

Page 8: Debugging Polymorphism and Interface Applet Hands on Computing with Java

• Fact: The bug that corresponds to the compilation error message could appear anywhere before or at the line indicated by the compiler.

• What should you do?– Inspect the code backward starting at the line indicated

by the compiler (usually just within few lines)

– Divide and conquer: Use /* … */ to comment out the block of codes that may contain the bug, then gradually reduce the search range.

I can't find the error at line xxx!

Page 9: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Don't panic!• Ignore the error message and just inspect the code around

the line indicated by the compiler

Don't give up easily!• Try harder for a little longer (After all, it is your code.)

• "Google" the error message for possible solutions

• Last resort: Ask TAs or teachers

I don't know what these compilation errors mean!

•illegal start of type•'class' or 'interface' expected•cyclic inheritance involving Main•blank final

Page 10: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Outline• Compilation Errors

– Typical Causes of Compilation Errors– Strategy for locating and fixing compilation errors

• Runtime/Logical Errors– Typical Causes of Runtime or Logical Errors– Strategy for locating and fixing logical errors

• Debugging programs with IDE (NetBeans)

• Interpreting Stack Trace of an Exception• Adding codes to help detecting bugs

Page 11: Debugging Polymorphism and Interface Applet Hands on Computing with Java

• Uninitialized Variables

• Forget to create an object using the "new" operator before using the objecte.g.: String s;

int len = s.length();

• Miscalculated index rangee.g.: String s = "abc";

char lastLetter = s.charAt(3);

• Implemented a "wrong" solution

Typical Causes of Runtime Errors

Page 12: Debugging Polymorphism and Interface Applet Hands on Computing with Java

// A program to compute interestclass CalculateInterest {

public static void main(String args[]) { double interestRate, principal, interest; int months;

// Input …

// Calculation …

// Output … }}

Principal)12

ateInterest R1(*PrincipalInterest Months

Suppose this program always prints the interest as $0.00.

What could go wrong?

How should you approach to locate the bug?

Page 13: Debugging Polymorphism and Interface Applet Hands on Computing with Java

• Inspect the value of variables

– The behavior or the output of your program depend on the values of some variables.

Basic approaches to find bugs

Page 14: Debugging Polymorphism and Interface Applet Hands on Computing with Java

• Inspect the value of variables– Select some input values which you know what

the output is

– Decide which variables to inspect and where to inspect them

– Print the value of the variables (to see if they match your expected values)

Basic Approaches To Locate Bugs

Page 15: Debugging Polymorphism and Interface Applet Hands on Computing with Java

class CalculateInterest {

public static void main(String args[]) { double interestRate, principal, interest; int months;

// Input …

// Calculation …

// Output … }}

Input: Does not depend on any variable

Calculation: Depends on interestRate, principal, and months

Output: Depends on interest

Decide which variables to inspect

Page 16: Debugging Polymorphism and Interface Applet Hands on Computing with Java

class CalculateInterest { public static void main(String args[]) { double interestRate, principal, interest; int months;

// Input …

System.out.println("Before calculation: "); System.out.println("interestRate = " + interestRate); System.out.println("principal = " + principal); System.out.println("months = " + months); // Calculation …

System.out.println("Before output: "); System.out.println("interest = " + interest); // Output … }}

Output the value of the dependent variables

Page 17: Debugging Polymorphism and Interface Applet Hands on Computing with Java

• Sometimes you may only want to debug part of your program because …– The rest of the code have already been fully test

ed

– Execution time is long• e.g: You only want to test the output part but the calc

ulation part takes several hours to complete

– That's the only part that you write/modify.

Debugging part of program

Page 18: Debugging Polymorphism and Interface Applet Hands on Computing with Java

class CalculateInterest { public static void main(String args[]) { double interestRate, principal, interest; int months;

// Input …

interestRate = 0.12; // 12% principal = 10000; months = 2; // Expected interest is 201 // Calculation … System.out.println("interest = " + interest);

// Output … }}

Debugging only the "Calculation" part …

Manually set the value of the dependent variables

Check the calculated value against the expected value

Page 19: Debugging Polymorphism and Interface Applet Hands on Computing with Java

class CalculateInterest { public static void main(String args[]) { double interestRate, principal, interest; int months;/* // Input …*/ interestRate = 0.12; // 12% principal = 10000; months = 2; // Expected interest is 201 // Calculation … System.out.println("interest = " + interest);/* // Output …*/ }}

Debugging only the "Calculation" part …

Optionally, comment the codes that are not subject to testing

Page 20: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Outline• Compilation Errors

– Typical Causes of Compilation Errors– Strategy for locating and fixing compilation errors

• Runtime/Logical Errors– Typical Causes of Runtime or Logical Errors– Strategy for locating and fixing logical errors

• Debugging programs with IDE (NetBeans)

• Interpreting Stack Trace of an Exception• Adding codes to help detecting bugs

Page 21: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Introduction

How can IDE help you in debugging your programs?

– Visual debugger (easy to use)

– Allows you to specify where to pause an executing program

– Allows you to inspect the value of the variables when a program is paused

– Allows you to trace your program execution

Page 22: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Running Program in Debugging Mode

• Run Main Project (F6)– Execute the program in normal mode

• Debug Main Project (Ctrl+F5)– Execute the program in debugging mode– Debugger can pause a program ONLY WHEN

you are running the program in debugging mode

Page 23: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Specifying Where To Pause A ProgramA breakpoint typically represents a location (usually a line of code) where an executing program is paused.

To toggle (set or remove) a breakpoint at a line of code, click at the spot in the left grey area next to the line in the editing window.

A small red square indicates that a break point is set at that line.

Multiple breaks points are allowed.

Page 24: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Inspecting Value of Variables

When a program is paused, you can view the value of the variables through:

• "Local Variables" window (Alt-Shift-1)– Automatically shows all the initialized local

variables

• "Watches" window (Alt-Shift-2)– Shows only the variables added manually by

the programmer.

Page 25: Debugging Polymorphism and Interface Applet Hands on Computing with Java

In Between Breakpoints

When you want to continue running your program, you can use

• Continue (F5)– continue execution until next breakpoint is

encountered

• Step– Take one "step" of execution and pause– How big is one step?

Page 26: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Stepping

• Step Over (F8)– Execute one line of code and pause

• Step Into (F7)– If a line of code involves a method call, go into the

method if possible and pause

– Otherwise, execute one line of code and pause

• Step Out (Ctrl-F7)– Execute the remaining lines of codes in the current

method and pause

Page 27: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Other Features

• Run to cursor (F4)– Use the cursor in the editing window as a temporary

breakpoint so execution will pause at the cursor.

• Finish Debugger Session (Shift-F5)– Stop debugging the program

Page 28: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Outline• Compilation Errors

– Typical Causes of Compilation Errors– Strategy for locating and fixing compilation errors

• Runtime/Logical Errors– Typical Causes of Runtime or Logical Errors– Strategy for locating and fixing logical errors

• Debugging programs with IDE (NetBeans)

• Interpreting Stack Trace of an Exception• Adding codes to help detecting bugs

Page 29: Debugging Polymorphism and Interface Applet Hands on Computing with Java

From time to time, you may come across error messages that look like this.

How should you interpret the message?

Try clicking on the lines with “at java….”

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: St

ring index out of range: 3

at java.lang.String.charAt(String.java:558)

at javaapplication1.Main.someMethod(Main.java:33)

at javaapplication1.Main.main(Main.java:27)

Interpreting Stack Trace of an Exception

Page 30: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Adding codes to help detecting bugs

• 預防勝於治療• You can minimize runtime errors in your progra

m by adding code to check variables against invalid values.

• e.g.:// Before calculate interest …

if (month < 0 || principal < 0.0 ||

interestRate < 0.0) {

// Print an error message and perhaps

// write code to recover from the error.

}

Page 31: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Summary

• Techniques for locating and fixing compilation errors

• Techniques for locating and fixing runtime/logical errors

• Using the debugger integrated in NetBeans to debug programs

Page 32: Debugging Polymorphism and Interface Applet Hands on Computing with Java

3-Minute Soft Break

Next…revision on OO concepts,

to introduce Polymorphism

Page 33: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Subclass Object Reference

• Given the following subclass relationship:class OctopusWatch extends Octopus

Octopus(class)

OctopusWatch(class)

Page 34: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Subclass Object Reference

• Do you recall:short s = 999;

OctopusWatch myWatch = new OctopusWatch(“Michael Fung”);

OctopusWatch(object)

Octopus(class)myWatch

OctopusWatch(class)

Page 35: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Subclass Object Reference

• Super-class object reference to sub-class object:short s = 999;

int i = s; // copy value of s to i

OctopusWatch myWatch = new OctopusWatch(“Michael Fung”);

Octopus anOctopus = myWatch; // copy object reference

OctopusWatch(object)

Octopus(class)myWatch anOctopus

OctopusWatch(class)

Page 36: Debugging Polymorphism and Interface Applet Hands on Computing with Java

General VS Special

• A super-class type is considered to be general.• A sub-class type is said to be special.

• Why?

• Because we supplement the sub-class– Adding fields and methods

• Thus, an object of the sub-class type is also considered to be an object of the super-class type.

Page 37: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Limit Yourself

• Super-class object reference to sub-class object:

OctopusWatch myWatch = new OctopusWatch(“Michael Fung”);myWatch.showTime(); // ok

Octopus anOctopus = myWatch; // copy object referenceanOctopus.addValue(100); // okanOctopus.showTime(); // invalid operation

myWatch.useValue(6.5); // ok

• Object reference of the super-class type cannot refer to the fields/methods newly defined by the sub-class.

Page 38: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Michael’s Nature Example

Inheritance is also known as specialization!

Page 39: Debugging Polymorphism and Interface Applet Hands on Computing with Java

What For?

• Dynamic binding or known as Polymorphism.

• By overriding a method declared in the super-class, we may send the same message to different objects of different (class) type.

Page 40: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Polymorphism

• Super-class object reference to sub-class object:

OctopusWatch myWatch = new OctopusWatch(“Michael Fung”);Octopus myCard = new Octopus(“Microphone”);

Octopus anOctopus; // an object referenceanOctopus = myWatch; // copy object referenceanOctopus.useValue(10.2); // okanOctopus = myCard; // copy object referenceanOctopus.useValue(6.5); // ok

• The object anOctopus via which in fact is sometimes sending messages to an Octopus object while sometimes to an OctopusWatch object.

Page 41: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Better Design Methodology

• This supports incremental development.

• We may create new classes from existing ones and override their methods.

• In such case, messages sending to these “new” objects may behave differently.

Page 42: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Backward Type Casting

• Backward type casting needs an explicit target type:

OctopusWatch myWatch = new OctopusWatch(“Michael Fung”);

Octopus anOctopus; // an object referenceanOctopus = myWatch; // copy object referenceanOctopus.useValue(10.2); // ok

OctopusWatch aWatch;aWatch = (OctopusWatch) anOctopus; // specializingaWatch.showTime(); // ok then

• Beware of the type given!!!– It must be a correct/compatible one!

Page 43: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Abstraction Through Interfaceinterface InterfaceIdentifier{

type1 method1(parameter1);type2 method2(parameter2);...

}

class ClassIdentifier implements Interface1, Interface2{

type1 method1(parameter1){}

type2 method2(parameter2){}...

}

Page 44: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Interface

• An interface is a specification.

• It is a standard.

• It is a list of method signatures.

• It is a guarantee: any class that implements this interface is guaranteed to provide these methods.

Page 45: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Example

• The AWT uses interfaces extensively.interface MouseMotionListener{ // simplified version

public void mouseDragged(MouseEvent e);public void mouseMoved(MouseEvent e);

}

// in some Component class:void addMouseMotionListener(MouseMotionListener obj);

• The method is not requesting a class type or primitive type parameter.

• It is requesting a parameter of ANY class type that meets the MouseMotionListener standard.

Page 46: Debugging Polymorphism and Interface Applet Hands on Computing with Java

3-Minute Soft Break

Next…Java Applet

Page 47: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Applet

• Mini-application run by a browser

• A number of security restrictions on what applets can do e.g. local file system

• Extends applet and overriding some standard methods

• Browser will invoke your method when some events happen e.g. initialization

Page 48: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Applet

• init()called when applet first loaded, pefrorming initialisation

• destroy()called when unloading, for freeing resources

• stop()called when temporarily invisible e.g scrolling

• getAppletInfo()get information about the applet i.e. a string

• paint()browser invokes to ask the applet draw itself

• mouseDown()responds to mouse click

Page 49: Debugging Polymorphism and Interface Applet Hands on Computing with Java

Appletimport java.applet.*; import java.awt.*;

public class FirstApplet extends Applet { public void paint(Graphics pen) { pen.drawString("Hello World", 25, 50); }}

• With the following HTML file applet.html

<APPLET code="FirstApplet.class" width="150" height="100"></APPLET>

Compile the above FirstApplet.java to FirstApplet.class