outline §abstract class and interface §inner classes and initialization blocks §equality...

64

Upload: oswin-ferguson

Post on 28-Dec-2015

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads
Page 2: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Outline

Abstract class and interfaceInner classes and initialization blocks

EqualityExceptionThreads

Page 3: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

The abstract Modifier

The abstract class Cannot be instantiated Should be extended and implemented in

subclasses

The abstract method Method signature without implementation

Page 4: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Abstract Classes

GeometricObjectGeometricObject CircleCircle CylinderCylinder RectangleRectangle

Circle -radius: double +getRadius(): double +setRadius(radius: double): void

Cylinder

-length: double +getLength(): double +setLength(length: double): void +findVolume(): double

GeometricObject -color: String -filled: boolean +getColor(): String +setColor(String color): void +isFilled(): boolean +setFilled(boolean filled): void +findArea(): double +findPerimeter(): double

Object

Rectangle -width: double -length: double +getWidth(): double +setWidth(width: double): void +getLength(): double +setLength(length: double): void

UML Notation: The abstract class name and the abstract method names are italicized.

Page 5: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Note

An abstract method cannot be contained in a nonabstract class.

If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be declared abstract. In other words, in a nonabstract subclass extended from an abstract class, all the abstract methods must be implemented, even if they are not used in the subclass.

Page 6: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Note

An abstract class cannot be instantiated using the new operator, but you can still define its constructors, which are invoked in the constructors of its subclasses.

For instance, the constructors of GeometricObject are invoked in the Circle class and the Rectangle class.

Page 7: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Note

A class that contains abstract methods must be abstract. However, it is possible to declare an abstract class that contains no abstract methods. In this case, you cannot create instances of the class using the new operator. This class is used as a base class for defining a new subclass.

Page 8: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Note

A subclass can be abstract even if its superclass is concrete. For example, the Object class is concrete, but its subclasses, such as GeometricObject, may be abstract.

Page 9: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Note

A subclass can override a method from its superclass to declare it abstract. This is rare, but useful when the implementation of the method in the superclass becomes invalid in the subclass. In this case, the subclass must be declared abstract.

Page 10: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Note

You cannot create an instance from an abstract class using the new operator, but an abstract class can be used as a data type.

Therefore, the following statement, which creates an array whose elements are of GeometricObject type, is correct.

GeometricObject[] geo = new GeometricObject[10];

Page 11: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Polymorphism

Consider the code in the next page:

What is the output?

Page 12: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

public class Test { public static void main(String[] args) { m(new A()); //?? m(new B()); //?? m(new C()); //?? m(new Object()); //?? } public static void m(Object o) { System.out.println(o.toString()); }}class A extends B {}class B extends C { public String toString() { return "B"; }}class C extends Object { public String toString() { return "C"; }}

Page 13: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

public class Test { public static void main(String[] args) { m(new A()); // B m(new B()); //B m(new C()); //C m(new Object()); //java.lang.Object@192d342 } public static void m(Object o) { System.out.println(o.toString()); }}class A extends B {}class B extends C { public String toString() { return "B"; }}class C extends Object { public String toString() { return "C"; }}

Page 14: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Polymorphism

Method m (Line 9) takes a parameter of the Object type. You can invoke m with any objects (e.g. new A(), new B(), new C(), and new Object())in Lines (3-6). An object of a subclass can be used by any code designed to work with an object of its superclass. This feature is known as polymorphism (from a Greek word meaning “many forms”).

Page 15: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Dynamic Binding

When the method m is executed, the argument x’s toString method is invoked. x may be an instance of A, B, C, or Object. Classes A, B, C, and Object have their own implementation of the toString method. Which implementation is used will be determined dynamically by the Java Virtual Machine at runtime. This capability is known as dynamic binding.

Page 16: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Dynamic Binding, cont.

Dynamic binding works as follows: Suppose an object o is an instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a subclass of C2, C2 is a subclass of C3, ..., and Cn-1 is a subclass of Cn. That is, Cn is the most general class, and C1 is the most specific class. In Java, Cn is the Object class. If o invokes a method p, the JVM searches the implementation for the method p in C1, C2, ..., Cn-1 and Cn, in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked.

Page 17: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

toString() method

The toString() method returns a string representation of the object.

The default implementation returns a string consisting of a class name of which the object is an instance, the at sign (@), and a number representing this object.

Page 18: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Generic Programming

Polymorphism allows methods to be used generically for a wide range of object arguments. This is known as generic programming. If a method’s parameter type is a superclass, you may pass an object to this method of any of the parameter’s subclasses. When an object is used in the method, the particular implementation of the method of the object that is invoked is determined dynamically.

Page 19: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

NoteMatching a method signature and binding a

method implementation are two issues.

The compiler finds a matching method according to parameter type, number of parameters, and order of the parameters at compilation time.

A method may be implemented in several subclasses. The JVM dynamically binds the

implementation of the method at runtime.

Page 20: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Interfaces

What Is an Interface?

Creating an Interface

Implementing an Interface

Page 21: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Creating an Interface

modifier interface InterfaceName { constants declarations; methods signatures;}

Page 22: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Example of Creating an Interface

// This interface is defined in

// java.lang package

public interface Comparable {

public int compareTo(Object o);

}

Page 23: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Generic max Method

public class Max {

// Return the maximum between two //objects

public static Comparable max

(Comparable o1, Comparable o2) {

if (o1.compareTo(o2) > 0)

return o1;

else

return o2;

}

}

Page 24: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Interfaces vs. Abstract Classes

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. An abstract class must contain at least one abstract method or inherit from another abstract method.

Page 25: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Interfaces vs. Abstract Classes, cont.

Since all the methods defined in an interface are abstract methods, Java does not require you to put the abstract modifier in the methods in an interface, but you must put the abstract modifier before an abstract method in an abstract class.

Page 26: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Inner Classes

Inner class: A class is a member of another class.

Advantages: In some applications, you can use an inner class to make programs simple.

An inner class can reference the data and methods defined in the outer class in which it nests, so you do not need to pass the reference of the outer class to the constructor of the inner class.

Page 27: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

// ShowInnerClass.java: Demonstrate using inner classespublic class ShowInnerClass { private int data; // A method in the outer class public void m() { // Do something InnerClass instance = new InnerClass(); } // An inner class class InnerClass { public void mi() { // A method in the inner class // Directly reference data and method defined in its outer class data++; m(); } }}

// ShowInnerClass.java: Demonstrate using inner classespublic class ShowInnerClass { private int data; // A method in the outer class public void m() { // Do something InnerClass instance = new InnerClass(); } // An inner class class InnerClass { public void mi() { // A method in the inner class // Directly reference data and method defined in its outer class data++; m(); } }}

Page 28: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Initialization BlockInitialization blocks can be used to initialize objects along with the constructors.

An initialization block is a block of statements enclosed inside a pair of braces.

An initialization block appears within the class declaration, but not inside methods or constructors.

It is executed as if it were placed at the beginning of every constructor in the class.

Page 29: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Initialization Block

public class Book {

{

numOfObjects++;

}

}

Page 30: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Static Initialization Block

A static initialization block is much like a nonstatic initialization block except that it is declared static, can only refer to static members of the class, and is invoked when the class is loaded.

Page 31: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Static Initialization Block

class A extends B {

static {

System.out.println("A's static initialization block is invoked");

}

class B {

static {

System.out.println("B's static initialization block is invoked");

}

}

Page 32: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

equals() method

The equals() method compares the contents of two objects.

The default implementation of the equals method in the Object class is as follows:

public boolean equals(Object obj) {return (this == obj);

}

Page 33: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

== vs. equals()

The == comparison operator is used for comparing two primitive data type values or for determining whether two objects have the same references.

The equals method is intended to test whether two objects have the same contents, provided that the method is modified in the defining class of the objects.

The == operator is stronger than the equals method, in that the == operator checks whether the two reference variables refer to the same object.

Page 34: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

A Rectangle Classpublic class Rectangle { private int upperleftX, upperleftY, downrightX, downrightY; public Rectangle(int x1, int y1, int x2, int y2) {

upperleftX = x1; upperleftY = y1; downrightX = x2; downrightY = y2; } public String toString() { return ”Upperleft = " + upperleftX + “,“ + upperleftY

+ ”; downright = " + downrightX + ”,” + downrightY; } public boolean equals(Object obj) { if(((Rectangle)obj).upperleftX == upperleftX &&

((Rectangle)obj).upperleftY == upperleftY &&((Rectangle)obj).downrightX == downrightX &&((Rectangle)obj).downrightY == downrightY) return true;

else return false; } public void setSize(int width, int height) {

downrightX = upperleftX + width; downrightY = upperleftY + height; } }

Page 35: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

equals() examplepublic void objectVariables(String[] args) {

Rectangle rect1 = new Rectangle(5, 10, 15, 20);Rectangle rect2 = new Rectangle(5, 10, 15, 20);;System.out.println("rect1 == rect2: " + (rect1 == rect2)); //??System.out.println("rect1.equals(rect2): " + rect1.equals(rect2)); //??rect1 = rect2;rect2.setSize(50, 100); // (newWidth, newHeight)System.out.println("rect 1: " + rect1.toString() );System.out.println("rect 2: " + rect2.toString() );System.out.println("rect1 == rect2: " + (rect1 == rect2)); //??System.out.println("rect1.equals(rect2): " + rect1.equals(rect2)); //??int x = 12;int y = 12;System.out.println("x == y: " + (x == y) ); //??x = 5;y = x;x = 10;System.out.println("x == y: " + (x == y) ); //??System.out.println("x value: " + x + "\ty value: " + y);

}

Page 36: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

equals() example: resultpublic void objectVariables(String[] args) {

Rectangle rect1 = new Rectangle(5, 10, 15, 20);Rectangle rect2 = new Rectangle(5, 10, 15, 20);;System.out.println("rect1 == rect2: " + (rect1 == rect2)); //falseSystem.out.println("rect1.equals(rect2): " + rect1.equals(rect2)); //truerect1 = rect2;rect2.setSize(50, 100); // (newWidth, newHeight)System.out.println("rect 1: " + rect1.toString() );System.out.println("rect 2: " + rect2.toString() );System.out.println("rect1 == rect2: " + (rect1 == rect2)); //trueSystem.out.println("rect1.equals(rect2): " + rect1.equals(rect2)); //trueint x = 12;int y = 12;System.out.println("x == y: " + (x == y) ); //truex = 5;y = x;x = 10;System.out.println("x == y: " + (x == y) ); //falseSystem.out.println("x value: " + x + "\ty value: " + y);

}

Page 37: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Equality versus Identity

confusion over equality and identity identity: two things are in fact the same thingequality: two things are for all practical

purposes alike, but not the exact same thing== versus the .equals method

use the equals method when you want to check the contents of the pointee, use == when you want to check memory addresses

Page 38: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

How to Handle Errors?It is possible to detect and handle errors of

various types.Problem: this complicates the code and

makes it harder to understand. the error detection and error handling code have

little or nothing to do with the real code is trying to do.

A tradeoff between ensuring correct behavior under all possible circumstances and clarity of the code

Page 39: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

ExceptionsMany languages, including Java use a

mechanism know as Exceptions to handle errors at runtime In Java Exception is a class with many

descendants. ArrayIndexOutOfBoundsException NullPointerException FileNotFoundException ArithmeticException IllegalArgumentException

Page 40: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Unchecked ExceptionsExceptions in Java fall into two different

categories checked and unchecked

unchecked exceptions are completely preventable and should never occur. (They are caused by logic errors, created by us, the programmers.)

Descendents of the RuntimeException class Examples: ArrayIndexOutOfBoundsException,

NullPointerException, ArithmeticException There does not need to be special error handling code If error handling code was required programs would be

unwieldy because so many Java statements have the possibility of generating or causing an unchecked Exception

Page 41: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Checked ExceptionsChecked exceptions represent conditions

that, although exceptional, can reasonably be expected to occur, and if they do occur must be dealt with in some way (other than the program terminating).

Unchecked exceptions are due to a programming logic error, your fault and preventable if coded correctly

Checked exceptions represent errors that are unpreventable by you!

Page 42: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

try-catch Format

try{ code that might throw an exception;}catch (exception_type_1 e){ code to handle exception of type 1;}...catch (exception_type_n e){ code to handle exception of type n;}

code that can cause an unchecked exception doesnot need to be placed in a try-catch block, but if anunchecked exception occurs and is not caught theprogram will stop

Page 43: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Dealing with exceptions if a method has code that could generate a checked

exception it must either deal with it or declare it can throw an exception of the type (passes the problem

onto the methods that call it)

public void method1(){ try

{ method2();}catch(ExceptionType1 e){ doErrorProcessing;}

}public void method2() throws ExceptionType1{ methodThatThrowsExceptionType1; }

Page 44: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

When an Exception Occurs If an exception occurs flow of control is shifted

out of the try block or method where it occurredThe skipped code is not executeda finally clause or block can be included after

a try catch block. Code in the finally clause is always executed

after the execution in the try block ends (by normal completion or because of an exception)

code in the finally block always executes before searching for catch blocks to handle an exception

used to clean up resources

Page 45: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Example

public boolean searchFor(String file, String word) throws

StreamException{ Stream input = null;

try{ input = new Stream(file);

while(!input.eof()){ if(input.next().equals(word))

return true;}// word not found in filereturn false;

}finally{ if(input != null)

input.close();}

}

Page 46: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Threads Concept

Multiple threads on multiple CPUs

Multiple threads sharing a single CPU

Page 47: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Creating Threads by Extending the Thread class

// Custom thread class public class CustomThread extends Thread { ... public CustomThread(...) { ... } // Override the run method in Thread public void run() { // Tell system how to run custom thread ... } ... }

// Client class public class Client { ... public someMethod() { ... // Create a thread CustomThread thread = new CustomThread(...); // Start a thread thread.start(); ... } ... }

Page 48: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Using the Thread Class to Create and Launch Threads

Objective: Create and run three threads: The first thread prints the letter a 100 times. The second thread prints the letter b 100 times. The third thread prints the integers 1 through

100.

Page 49: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Example 1:Using the Thread Class to

Create and Launch Threads, cont.

TestThreadTestThread

RunRun

Page 50: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Creating Threads by Implementing the Runnable Interface

// Custom thread class public class CustomThread implements Runnable { ... public CustomThread(...) { ... } // Implement the run method in Runnable public void run() { // Tell system how to run custom thread ... } ... }

// Client class public class Client { ... public static void main(String[] args) { ... // Create an instance of CustomThread CustomThread customThread = new CustomThread(...); // Create a thread Thread thread = new Thread(customThread); // Start a thread thread.start(); ... } ... }

Page 51: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Example 2: Using the Runnable Interface to Create and Launch Threads

Objective: Create and run three threads: The first thread prints the letter a 100 times. The second thread prints the letter b 100 times. The third thread prints the integers 1 through

100.

TestRunnableTestRunnable RunRun

Page 52: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Controlling Threads and Thread States

void run() Invoked by the Java runtime system to execute the thread. You must override this method and provide the code you want your thread to execute.

void start()

Starts the thread, which causes the run() method to be invoked. Called by the runnable object in the client class.

static void sleep(long millis)throws InterruptedException

Puts the runnable object to sleep for a specified time in milliseconds.

Page 53: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Controlling Threads and Thread States, cont.

void stop()

Stops the thread. (deprecated in JDK 1.2)

void suspend() (deprecated in JDK 1.2)

Suspends the thread. Use the resume() method to resume.

void resume() (deprecated in JDK 1.2)

Resumes the thread suspended with the suspend() method.

Page 54: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Thread Priority

Each thread is assigned a default priority of Thread.NORM_PRIORITY. You can reset the priority using setPriority(int priority).

Some constants for priorities include Thread.MIN_PRIORITY Thread.MAX_PRIORITY Thread.NORM_PRIORITY

Page 55: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Thread States

Page 56: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Thread Groups

Construct a thread group using the ThreadGroup constructor:

ThreadGroup g = new ThreadGroup("timer thread group");

Place a thread in a thread group using the Thread constructor:

Thread t = new Thread(g, new ThreadClass(), "This thread");

Page 57: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Thread Groups, cont.

To find out how many threads in a group are currently running, use the activeCount() method:

System.out.println("The number of “

+ “ runnable threads in the group ”

+ g.activeCount());

Page 58: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Synchronization

A shared resource may be corrupted if it is accessed simultaneously by multiple threads. For example, two unsynchronized threads accessing the same bank account causes conflict.

Step balance thread[i] thread[j]

1 0 newBalance = bank.getBalance() + 1;

2 0 newBalance = bank.getBalance() + 1;

3 1 bank.setBalance(newBalance);

4 1 bank.setBalance(newBalance);

Page 59: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Example 3: Showing Resource Conflict

Objective: create and launch 100 threads, each of which adds a penny to a piggy bank. Assume that the piggy bank is initially empty.

Page 60: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Example 3, cont

PiggyBankWithoutSyncPiggyBankWithoutSync RunRun

PiggyBank

-balance

+getBalance+setBalance

1

100

PiggyBankWithoutSync

-PiggyBank bank-Thread[] thread

+main

Object

-char token

+getToken+setToken+paintComponet+mouseClicked

Object

-char token

+getToken+setToken+paintComponet+mouseClicked

AddAPennyThread

+run()

Thread

-char token

+getToken+setToken+paintComponet+mouseClicked

1

1

... }}

Page 61: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Creating a Thread to run the while loop, cont.

public void run() { while (true) { repaint(); try { thread.sleep(1000); waitForNotificationToResume(); } catch (InterruptedException ex) {

} }}

Page 62: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Creating a Thread to run the while loop, cont.

private synchronized void

waitForNotificationToResume()

throws InterruptedException {

while (suspended)

wait();

}

Page 63: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Creating a Thread to run the while loop, cont.

public synchronized void resume() {

if (suspended) {

suspended = false;

notify();

}

}

public synchronized void suspend() {

suspended = true;

}

Page 64: Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads

Example 4: Displaying a Running Clock in in an Applet

Objective: Simulate a running clock by using a separate thread to repaint the clock.

ClockAppletClockApplet Run Applet ViewerRun Applet Viewer