Top Banner
More on Java 1 More On Java CS4280 Advanced Internet Applications Development
84
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: JavaOO

More on Java 1

More On Java

CS4280 Advanced Internet Applications

Development

Page 2: JavaOO

More on Java 2

Contents

• Encapsulation and Information Hiding

• Constructors and Finalizers

• Abstract class, Interface and Inheritance

• Polymorphism Overloading, Dynamic Binding

• Package in Java

• Exceptions

Michael
Highlight
Page 3: JavaOO

More on Java 3

Encapsulation and Information Hiding

• OOP encapsulates data and method into objects.

• A system / program is a collection of objects to perform special task

• Objects communicate with one another across well-defined interfaces.

Page 4: JavaOO

More on Java 4

Encapsulation and Information Hiding

• In Java, the unit of programming is the class (Object is an instance of a class)

• OOP programmer concentrate on creating their own user-defined type called classes (Also referred as programmer-defined types)

• Class contains data and the set of methods that manipulate the data

Page 5: JavaOO

More on Java 5

Encapsulation and Information Hiding

Page 6: JavaOO

More on Java 6

Information Hiding

• Classes normally hide their implementation details from the clients of the classes

• Using Set and Get methodspublic class Time1{

private int hour;public void setHour(int h){

hour=h;}public int getHour(){

return hour;}

}

• Private instance variables can be manipulated only by methods of the class

Page 7: JavaOO

More on Java 7

Object-Oriented Programming in Java

• Similarities with C++

– User-defined classes can be used the same way as built-in types.

– Basic syntax

• Differences from C++

– Methods (member functions) are the only function type

– Object is the topmost ancestor for all classes

– All methods use the run-time, not compile-time, types (i.e. all

Java methods are like C++ virtual functions)

– The types of all objects are known at run-time

Single inheritance only

Page 8: JavaOO

More on Java 8

Object-Oriented Nomenclature

• “Class” means a category of things

– A class name can be used in Java as the type of a field or local

variable or as the return type of a function (method)

• “Object” means a particular item that belongs to a

class

– Also called an “instance”

For example, consider the following line:

String s1 = "Hello";

– Here, String is the class, and the variable s1 and the value

"Hello" are objects (or “instances of the String class”)

Page 9: JavaOO

More on Java 9

Abstract Data Type

• The concept of data abstraction is that the client of an class does not need to know how the class is implemented but only the rule of access (what will be done rather than how it will be done)

• Java classes defined abstract data types (ADTs) I.e. The primary activity in Java is creating new data types (classes) and expressing the interactions among objects of those data types

Page 10: JavaOO

More on Java 10

Abstract Data Type

• ADTs improved the program development process by providing an additional formalization. However, it does not replace structured programming

• In fact, all data types (built-in: int, float / user defined: Time1) are only approximations or models of real-world concepts and behaviors (Mathematical integers has infinitive value while data type “int” only have 32 bits in size). Therefore, it already is an abstract data type

• ADT actually captures two notions: data representation and the operations that are allowed on that data.

Page 11: JavaOO

More on Java 11

Object Creation

• Object is an instance of class

Page 12: JavaOO

More on Java 12

Object Creation – Java Example

• ObjectReference = new className(Constructor Parameters)

• E.g public String s; //declare an object reference with “String” type

s=new String (“Hello World”); //Create the object

• When an object is created, the constructor will be called

Page 13: JavaOO

More on Java 13

Objects and References

• Once a class is defined, you can easily declare a variable (object reference) of the class

Ship s1, s2;

Point start;

Color blue;

• Object references are initially null

– The null value is a distinct type in Java and should not be considered equal to zero

– A primitive data type cannot be cast to an object (use wrapper classes)

• The new operator is required to explicitly create the object that is referenced

ClassName variableName = new ClassName();

Page 14: JavaOO

More on Java 14

Constructors and Finalizers

• Constructors

– Invoked automatically each time an object of the class is instantiated (created)

– Is a method with the same name as the class

– Cannot specify return types or return values, otherwise the default constructor will be called

– A class may contain overloaded constructors (more than one) to provide a variety of means for initializing objects of that class

Page 15: JavaOO

More on Java 15

Constructors and Finalizers

Page 16: JavaOO

More on Java 16

Constructors and Finalizers

Time1 t1, t2;

t1 = new Time1(); // call the first constructors

// public t1(){….}

t2 = new Time1(10,20,0); //call the second constructors

// public Time1(int h, int m, int s)

Page 17: JavaOO

More on Java 17

Default Constructor

• Compiler creates a default constructor that takes no arguments (no-argument constructor) if no constructor is defined for the class

• The default constructor calls the default constructor of its parent class and then initialize the instance variables according the following rules:

– Primitive numeric data type -> 0

– Booleans ->false

– Object references->null

Michael
Highlight
Page 18: JavaOO

More on Java 18

Finalizers

• System Resources, such as memory, may be acquired by an object when it was created

• Class in Java can have a finalizer method to return resources to the system

• It is guaranteed to be called to perform termination housekeeping on the object just before the garbage collector reclaims the memory for the object

• Always has the name finalize, receive no parameters and takes no arguments.

Michael
Highlight
Page 19: JavaOO

More on Java 19

Finalizers

Public class Employee extends Object{

private String firstName;

private String lastName;

private static int count;

public Employee (String fName, String lName){

firstName=fName

lastName=lName;

++count; //increment static count of employees

}

protected void finalize(){

--count; // decrement static count of employees

}

}

Page 20: JavaOO

More on Java 20

Static Modifier

• It indicates that the variables is shared by the entire class

• It can be accessed by the classname instead of just by an instance

• If a class Foo had a static variable bar

• foo1 = new Foo(); foo2=new Foo();

• Foo.bar, foo1.bar, foo2.bar are all the same shared variables

• Similar example is Math.cos

Page 21: JavaOO

More on Java 21

Abstract Classes

• Idea

– Abstract classes permit declaration of classes that define only part of

an implementation, leaving the subclasses to provide the details

• A class is considered abstract if at least one method in the class has no

implementation

– An abstract method has no implementation (known in C++ as a pure

virtual function)

– Any class with an abstract method must be declared abstract

– If the subclass overrides all the abstract methods in the superclass,

than an object of the subclass can be instantiated

• An abstract class can contain instance variables and methods that are fully

implemented

– Any subclass can override a concrete method inherited from the

superclass and declare the method abstract

Page 22: JavaOO

More on Java 22

Abstract Classes

• An abstract class cannot be instantiated, however references to an abstract class can be declared public abstract ThreeDShape {

public abstract void drawShape(Graphics g);

public abstract void resize(double scale);

}

ThreeDShape s1;

ThreeDShape[] arrayOfShapes

= new ThreeDShape[20];

• Classes from which objects can be instantiated are called concrete classes

Page 23: JavaOO

More on Java 23

Abstract Class

• Only abstract classes may have abstract methods

– methods that are declared but not yet implemented.

abstract class Point {

int x = 1, y = 1;

void move(int dx, int dy) {

x += dx;

y += dy;

alert();

}

abstract void alert();

}

Michael
Highlight
Page 24: JavaOO

More on Java 24

Abstract Class

• It is generally used as superclass in inheritance

• We can also refer them to abstract superclass

• The sole purpose of abstract class is to provide

an appropriate superclass from which other

class may inherit interface and/or

implementation

• Classes from which objects can be instantiated

are called concrete class

Page 25: JavaOO

More on Java 25

Abstract Classes

• It acts as a parent of other class but cannot be directly

instantiated

• It can provide some common behavior in the class

• The class does not have enough information to be used

by itself

• Java lets you declare a class abstract and the compiler

will not let you build an instance of it

Page 26: JavaOO

More on Java 26

Abstract Class, Interface and Inheritance

• An abstract class cannot be instantiated

– Point p=new Point(); // compile-time error

• A subclass of an abstract class that is not itself abstract

may be instantiated

class SimplePoint extends Point {

void alert() { }

}

Point p = new SimplePoint(); //Correct!

• A class type should be declared abstract only if the

intent is that subclasses can be created to complete

the implementation

Page 27: JavaOO

More on Java 27

Example Shape.java

// This appears in Core Web Programming from Prentice Hall Publishers, and may be freely

// used or adapted. 1997 Marty Hall, [email protected].

/** The parent class for all closed, open, curved, * and straight-edged shapes. */

public abstract class Shape {

protected int x, y;

public int getX() {

return(x); }

public void setX(int x) {

this.x = x; }

public int getY() {

return(y); }

public void setY(int y) {

this.y = y; }

}

Page 28: JavaOO

More on Java 28

Abstract Curve.java and StraightEdgeShape.java

public abstract class Curve extends Shape {

public Curve() { // CONSTRUCTOR implementation not available }}

public abstract class StraightEdgedShape extends Shape { public StraightEdgedShape()

{ // CONSTRUCTOR implementation not available }}

- you can extend Curve to create a circle and have circle to have a method to

calculate its area

- Then the circle class will have no abstract and include a getArea method

Page 29: JavaOO

More on Java 29

/** A circle extends from Curve. * */

public class Circle extends Curve {

private double radius;

public Circle(int x, int y, double radius) {

setX(x);

setY(y);

setRadius(radius);

getRadius()

}

public double getRadius() {

return(radius);

}

public void setRadius(double radius) {

this.radius = radius;

}

}

Page 30: JavaOO

More on Java 30

Java Interface

• Borrowed from the Objective-C protocol

• Used to identify a common set of methods for the group of

classes that implement the interface

• Also used to share constant between classes.

• Provide the benefits of multiple inheritance without its

implementation difficulties.

• Provide a Standard framework for accessing classes

Michael
Highlight
provide only one inheritance
Page 31: JavaOO

More on Java 31

Interfaces

• Idea

– Interfaces define a Java type consisting purely of constants and

abstract methods

– An interface does not implement any of the methods, but

imposes a design structure on any class that uses the interface

– A class that implements an interface must either provide

definitions for all methods or declare itself abstract

Page 32: JavaOO

More on Java 32

public interface Interface1 {

DataType CONSTANT1 = value1;

DataType CONSTANT2 = value2;

ReturnType1 method1(ArgType1 arg);

ReturnType2 method2(ArgType2 arg);

}

Interfaces

• Modifiers

– All methods in an interface are implicitly abstract and the

keyword abstract is not required in a method declaration

– Data fields in an interface are implicitly static final (constants)

– All methods in an interface are implicitly public

Michael
Highlight
Michael
Highlight
Michael
Highlight
Page 33: JavaOO

More on Java 33

Declaring

• InterfaceModifiers interface interfaceName ExtendsClause InterfaceBody

• E.g.

public interface Clickable{

int x=0, y=0;

void click();

void doubleClick();

}

• InterfaceModifiers could be abstract(default) and public

• Like class declaration, only one interface may be declared public in a given compilation unit(program file)

• All variables declared in an interface body are assumed to be both static and final

• All methods declared in an interface body are assumed to be abstract and do not have method bodies

• Only access methods can be declared (no constructor / finializier)

Page 34: JavaOO

More on Java 34

Interfaces

• Extending Interfaces

– Interfaces can extend other interfaces, which brings rise to sub-interfaces and super-interfaces

– Unlike classes, however, an interface can extend more than one interface at a timepublic interface Displayable extends Drawable, Printable {

// Additonal constants and abstract methods

...

}

• Implementing Multiple Interfaces

– Interfaces provide a form of multiple inheritance because a class can implement more than one interface at a time

public class Circle extends TwoDShape implements Drawable, Printable {

...

}

Page 35: JavaOO

More on Java 35

Implementing Interfaces

• To implement an Interface, use the keyword implements to introduce an implement clause of the class declaration.

• E.g. public class MyButton implements Clickable{

…….//Implementation of interface Clickablepublic void Click(){…….}//Implementation of interface Clickablepublic void doubleClick(){…….

}}

Page 36: JavaOO

More on Java 36

Interface

• An interface may have many methods. If a class

implements an interface, but only implements

some of its methods, then this class becomes

an abstract method. It cannot be instantiated.

Page 37: JavaOO

More on Java 37

Implementing Interfaces

Page 38: JavaOO

More on Java 38

Implementing Interfaces

• An interface reference (variable whose declared type is an interface) may refer to any instance of a class which implements the specified interface.

• E.g.public Clickable clickedObj;clickedObj=new MyButton();clickedObj=new MyIcon();clickedObj=new MyScrollBar();

• For a class that implement the interface, all the abstract methods must be declared in order to implement either by the class itself or one of its superclasses. Otherwise, the class is not implementing the interface.

Page 39: JavaOO

More on Java 39

Benefits of Interfaces

• Allow standard sets of methods to be used across the class hierarchy.

I.e. Interface defines the method signature (name of method , type and number of parameters it received) for all class that support those functionality. Therefore, it establishes a uniform approach to implementing these common operation

e.g.

public interface MouseMotionListener{public void mouseMove(int x, int y);// All implementing classes receive mouse move event // with the x, y coordination of the mouse pointer

public void mouseDrag(int x, int y);// All implementing classes receive mouse drag event// with the x, y coordination of the mouse pointer

}

Page 40: JavaOO

More on Java 40

Benefits of Interfaces

• Allow object to be referenced by the methods they support without considering the actual object being implemented (Dynamic binding- The decision as to what method to invoke is deferred until execution time)

• Considering the following method:

Page 41: JavaOO

More on Java 41

Benefits of Interfaces

• activeObject can be accessed according the method signatures defined in Interface Clickable

• e.g. activeObject.click();

/*ActiveObject may be an reference of MyButton/ My Icon / MyScrollbar but

the caller need not be awaked of it */

Page 42: JavaOO

More on Java 42

Inheritance

• Inheritance is a form of software reusability

• New classes (subclass) are created (inherit) from existing classes (superclass) by absorbing their attributes and behaviors

• Saves time in program development

• Java only supports single inheritance. I.e. a class is derived from one superclass.

• To derived from an existing class, use the keyword extends following by superclass’s name

Page 43: JavaOO

More on Java 43

Inheritance - Example

//Subclass//public class Circle extends Point{

protected double radius;public Circle(){

setRadius(0);}public Circle(double r, int a, int b){

super(a,b);setRadius( r);

}public void setRadius(double r){

radius=(r>0.0?r:0.0);}public void getRadius(){

return radius;}

}

//Superclass//public class Point{

protected int x, y;// coordinates of the Pointpublic Point(){

setPoint(0,0)}public Point(int a, int b){

setPoint(a,b);}public void setPoint(int a, int b){

x=a;y=b;}public int getX() {return x;}public int getY() {return y;}

}

Page 44: JavaOO

More on Java 44

Inheritance - Constructor

• Java automatically calls superclass’s default constructor(no-argument constructor) by default

• It is a compiling error If no default constructor can be found in the superclass

• The keyword super is used for calling the superclass’s constructor

public Circle(){

setRadius(0);

}

public Circle(){

super();

setRadius(0);

}

Michael
Highlight
Michael
Highlight
Page 45: JavaOO

More on Java 45

Inheritance - Constructor

• The call to the superclass constructor must be the first line in the body of the subclass constructor

• To call the superclass constructor other than default constructor, using the superclass constructor call syntax[I.e. keyword super followed by a set of parenthese containing the arguments to the superclass constructor.

– E.g. use “super (a,b);” in the constructor of circle will call the constructor “point(int a, int b)” in the class Point

Page 46: JavaOO

More on Java 46

Inheritance - Finalizer

• Java will not call the finalizer of superclass

• If you have defined the finalizer in your subclass, You should call the superclass finalizer at last

• E.g.

protected void finalize(){

// finalizer of circle.

……

……

// calling the superclass’s finalizer

super.finalize();

}

Page 47: JavaOO

More on Java 47

Multiple Inheritance - Interface

• Extends only define a subclass, thus, only one parent class

• Class does not support multiple inheritance

• Interface can be extends from more than one interfacepublic interface Icon extends Clickable, Movable{

// Clickable and Moveable are Java interface type………………..………………..

}

• Class that implements the interface Icon must declare all the functions defined in Clickable and moveable as well as those in Icon

Page 48: JavaOO

More on Java 48

Multiple Inheritance - Interface

public interface Movable {

void moveTo(int x, int y); //move to coordination x,y

int getX(); // get the x-coordination of the object

int getY(); // get the y-coordination of the object

}

public interface Icon extends Clickable, Movable{

String getFileName(); // get the filename of the icon

}

Page 49: JavaOO

More on Java 49

Multiple Inheritance - Interface

public class MyIcon implements Icon{

public void click(){ …. // Clickable‘s implementation

}

public void doubleClicke(){ // Clickable‘s implementation

}

public void moveTo(int x,int y){ // Movable‘s implementation

}

public int getX(){ …… // Movable‘s implementation

}

public int getY(){ …… // Movable‘s implementation

}

public String getFileName(){ // Icon ‘s implementation

}

}

Page 50: JavaOO

More on Java 50

Differences – Abstract Class and Interface

• In an interface, the data must be constants; an

abstract class can have all types of data

• Each method in an interface has only a

signature without implementation; an abstract

class can have concrete methods

• No abstract modifier appears in an interface,

you must put the abstract modifier before an

abstract method in an abstract class

Page 51: JavaOO

More on Java 51

Implicit Subclass-Object-to-Superclass

Object Conversion

• Subclass object “is a “ superclass object. I.e. subclass objects can be treated as superclass objects

– Point p=new Circle();

• Superclass objects cannot be assigned to a subclass reference

– Circle c=new Point(); //compiling error

Page 52: JavaOO

More on Java 52

Implicit Subclass-Object-to-Superclass

Object Conversion

– Referring to a superclass object with a superclass reference is

straightforward

• Point p=new Point();

– Referring to a subclass object with a subclass reference is

straightforward

• Circle c=new Circle();

– Referring to a subclass object with a superclass reference is safe

because the sub class object is an object of it its superclass as well.

(Only refer to superclass members

• Point p=new Circle();

• p.setPoint(1,2); // superclass member

• p.setRadius(2); // syntax error

– Referring to a superclass object with a subclass reference is a syntax

error Circle c =new Point();

Michael
Highlight
Michael
Highlight
Page 53: JavaOO

More on Java 53

Polymorphism

• Polymorphism refers to the ability of objects to have many methods of the same name but with different forms

• The compiler and runtime system matching each method invocation to the correct method, class, and object

• Compiler achieve polymorphism by method overloading

• Runtime system achieve polymorphism by dynamic binding

Michael
Highlight
Michael
Highlight
Michael
Highlight
Page 54: JavaOO

More on Java 54

Overloading

• Methods with same name but different signatures (parameters list) are said to be overloaded

• The overloaded methods must either– Both declared in the same class

– Both inherited by a class

– One declared and one inherited

• return types or throws clauses of two overloading methods could be different or same.

Page 55: JavaOO

More on Java 55

Overloading

• The following method is for the class Pointpublic void setPoint(int a, int b){ x=a;y=b;} // method 1

public void setPoint(Point p){ // method 2x=p.getX();

y=p.getY();

}

• When the method “setPoint” is called, the compiler will determine which

method should be invocated based on the parameters the caller supplied– setPoint(1,2); //method 1 will be called

– setPoint(new Point(12,14)); //method 2 will be called

– setPoint(p1); //p1 is an object of point. Method 2 will be called

Page 56: JavaOO

More on Java 56

Overloading

• Another method (method 3) is added to class Circle

public void setPoint(Circle c){

x=c.getX();

y=c.getY();

}

Page 57: JavaOO

More on Java 57

Dynamic (Method) Binding

• the capability to defer the decision of method invocation until runtime.

• I.e. The actual method and the corresponding object /class to be invocated may not

be known at the time of compilation.

Page 58: JavaOO

More on Java 58

Dynamic Binding - Java -

• Dynamic binding in Java is achieved by superclass reference and Interface type

• When an object reference is obtained as method parameter, the actual implementation is determined at run timeE.g. public void setPoint(Point p){

// The reference of p can be an object of class Point /Circle}

• When an object reference type is an interface type, the actual implementation is determined at run timeE.g. public void objectClicked(Clickable activeObject){

// The implementation of activeObject is supplied // by the caller

}

Page 59: JavaOO

More on Java 59

Package in Java

• In java, related classes and interfaces can be stored in a same directory to form a package

Page 60: JavaOO

More on Java 60

Package in Java

• Package defines the relationship among classes and

interfaces and its location

I.e. Related class can be found at same directory (folder)

• It also help to resolve name conflict among class and

interface

E.g. Class “Point” has also defined in the package “awt” of Java

Standard Library2 SDK. If both are imported into a compilation unit,

package name is used to resolve the ambiguity

java.awt.Point javaPoint; // Point class defined in java

MyLib.Graphic.Point myPoint; //Point class defined in myLib

Page 61: JavaOO

More on Java 61

Package in Java

• To import a class / package in the compilation unit, use Import <packageName.className>

Page 62: JavaOO

More on Java 62

Creating Package

• To create package in Java, use the “package “ statement with package name

package MyPackage;

public class ClassA{

protected String content;

public String toString(){

return “I am Class A, from MyPackage :”+content;

}

}

Page 63: JavaOO

More on Java 63

Creating Package

• To place the package under given root directory use tag “-d” while compiling the class

javac -d <root directory> programFile.java

e.g. javac -d c:\temp ClassA.java

(make sure the directory “c:\temp” do exist)

Page 64: JavaOO

More on Java 64

Creating Package

package MyLib.Graphic;

public class Point{

….

}

javac -d c:\temp Point.java

package MyLib.Graphic;

public class Line{

….

}

javac -d c:\temp Line.java

Page 65: JavaOO

More on Java 65

Creating Package

• To access the class within a given package, use the keyword import in the source file

import MyLib.ClassA;public class TestPackage{

public static void main(String[] args){ClassA a=new ClassA();System.out.println(a);

}}

• To compile the the class

javac -classpath c:\Mylib TestPackage.java

• To execute the program

java -classpath c:\Mylib; TestPackage

Page 66: JavaOO

More on Java 66

What is an Exception ?

• Is an event that disrupts the normal flow of instructions during the execution of a program.

• When an error occurs within a method, the method creates an object and hands it off to the runtime system

• Exception objects inherit from the Throwable class

Page 67: JavaOO

More on Java 67

Exception ?

• The exception object contains an information about the error including its type and state of the program

• Creating an exception object and handing it to the Runtime system is called throwing an exception

• After a method throws an exception, the runtime system attempts to find “something” to handle it.

• The set of possible “something” to handle the exception is the ordered list of methods that has been called to get to the method where the error occurred

• The code that handles the error is called exception handler

Page 68: JavaOO

More on Java 68

Exception Handling

• In Java, exception will be thrown when semantic constraints are violated and will cause a non-local transfer of control from the point where the exception occurred to a point that can be specified by the programmer

• An exception is said to be thrown from the point where it occurred and is said to be caught at the point to which control is transferred.

Page 69: JavaOO

More on Java 69

Exception Handling- Program without exception handling -

// sample code

int x=0;

int z=1/x;

z++;

Page 70: JavaOO

More on Java 70

Exception Handling- Program with Exception Handling -

// sample code

try{

int x=0;

int z=1/x;

z++;

}catch (ArithmeticException e){

System.out.print(“Except….”);

z=0;

}

System.out.println(“value of z”+z);

z++;

Page 71: JavaOO

More on Java 71

Exception Handling

• Compare with exception handling with C++

– Exception-handling construct (try/catch) has a finally clause that always get executed, regardless of whether or not an exception was thrown

– You can require users of your methods to handle exceptions your method generate. Otherwise, the code will not compile

Page 72: JavaOO

More on Java 72

Exception Handling

• Basic Form

Try{

statement1;

statement2;

}catch (SomeException someVar){

handleTheException(someVar);

}

Page 73: JavaOO

More on Java 73

Exception Handling

• A single try can have more than one catch.

Try{}catch(Exception1 e1){}catch(Exception2 e2){…}catch(ExceptionN eN){}

• If an exception is generated, Java executes the first catch clause that matches the type of exception thrown. Therefore, in general, a more specific exception type should be catch before a more general ones. Otherwise, syntax error occurs.

Page 74: JavaOO

More on Java 74

Exception Handling

Try{urlString=in.readLine();url=new URL(urlString);

}catch (MalformedURLException mue){getURL();

}catch (IOException ioe){return (null);

}

Since MalformedURLException is a subclass of IOException, therefore it should be catch first.

Michael
Highlight
Michael
Highlight
Michael
Highlight
Michael
Highlight
Page 75: JavaOO

More on Java 75

Exception Handling

• The finally clause that always get executed, regardless of whether or not exceptions are thrown. It is executed even if break, continue, or return is used within the try or catch clause.

Try{urlString=in.readLine();url=new URL(urlString);

}catch (MalformedURLException mue){System.out.println(“URL erro”);

}catch (IOException ioe){return (null);

}finally{System.out.println(“I am finally”);

}

Michael
Highlight
Michael
Highlight
Michael
Highlight
Page 76: JavaOO

More on Java 76

Exception Handling

public class Test{public static int functionA(){

try{int y;y=1/0;

}catch(ArithmeticException ae){System.out.println("ArithmeticException catch: "+ae);return 1;

}finally{System.out.println("I am finally");

}return 0;

} //end functionApublic static void main(String args[]){

int z=functionA();System.out.println("Function A return:"+z);

} //end main} //end class

Page 77: JavaOO

More on Java 77

Exception Handling

Result:

>ArithmeticException catch:

java.lang.ArithmeticException: / by zero

>I am finally

>Function A return:1

Page 78: JavaOO

More on Java 78

Exception Handling

try{int x;x=1/0;

}catch(NumberFormatException nfe){

System.out.println(“ Number format exception”+nfe);}catch(ArithmeticException ae){

System.out.println(“Arithms Exception:” +ae);}

Page 79: JavaOO

More on Java 79

Exception Handling

try{MyObject x=null;x.myFunctionA();//NullPointerException will be

thrown

}catch(NumberFormatException nfe){

System.out.println(“ Number format exception”+nfe);}catch(ArithmeticException ae){

System.out.println(“Arithms Exception:” +ae);}

Page 80: JavaOO

More on Java 80

Exception Handling

- Define an Exception -

• A customized exception can be make by subclassing any of the existing exception type

• E.g.public class MyException extends Exception{

public MyException(){super(“My exception throw”);

}public MyException(String message){super(message);

}}

Michael
Highlight
Page 81: JavaOO

More on Java 81

Class DivideByZero Exception

(extends Arithmetic Exception)

1 // Fig. 14.1: DivideByZeroException.java

2 // Definition of class DivideByZeroException.

3 // Used to throw an exception when a

4 // divide-by-zero is attempted.

5 public class DivideByZeroException

6 extends ArithmeticException {

7 public DivideByZeroException()

8 {

9 super( "Attempted to divide by zero" );

10 }

11

12 public DivideByZeroException( String message )

13 {

14 super( message );

15 }

16 }

17

Define our own exception class

(exceptions are thrown objects).

Default constructor (default message)

and customizable message

constructor.

Page 82: JavaOO

More on Java 82

Exception Handling- Throwing Exception -

• For a method that potentially generates one or more

exceptions that will not handle explicitly, it should

declared using throws construct as followpublic returnType Method (…) throws someException{

}

public returnType Method (…) throws exception1, exception 2,…exception3{

}

Page 83: JavaOO

More on Java 83

Exception Handling- Throwing Exception -

• To generate an exception, use the throw construct as

follow

{ …

throw new IOException();

//Exception will be thrown at this point

}

Page 84: JavaOO

More on Java 84

Example

// Definition of method quotient. Used to demonstrate

// throwing an exception when a divide-by-zero error

// is encountered.Fig.14.1 in book Dietel & Dietel

// catch it later

public double quotient( int numerator, int denominator )

throws DivideByZeroException

{

if ( denominator == 0 )

throw new DivideByZeroException();

return ( double ) numerator / denominator;

}

Michael
Highlight
Michael
Highlight