Download presentation
Presentation is loading. Please wait.
Published byOswin Ferguson Modified over 9 years ago
2
Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads
3
The abstract Modifier The abstract class l Cannot be instantiated l Should be extended and implemented in subclasses The abstract method l Method signature without implementation
4
Abstract Classes GeometricObjectCircleCylinderRectangle
5
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.
6
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.
7
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.
8
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.
9
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.
10
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];
11
Polymorphism Consider the code in the next page: What is the output?
12
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"; } }
13
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"; } }
14
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”).
15
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.
16
Dynamic Binding, cont. Dynamic binding works as follows: Suppose an object o is an instance of classes C 1, C 2,..., C n-1, and C n, where C 1 is a subclass of C 2, C 2 is a subclass of C 3,..., and C n-1 is a subclass of C n. That is, C n is the most general class, and C 1 is the most specific class. In Java, C n is the Object class. If o invokes a method p, the JVM searches the implementation for the method p in C 1, C 2,..., C n-1 and C n, in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked.
17
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.
18
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.
19
Note §Matching 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.
20
Interfaces §What Is an Interface? §Creating an Interface §Implementing an Interface
21
Creating an Interface modifier interface InterfaceName { constants declarations; methods signatures; }
22
Example of Creating an Interface // This interface is defined in // java.lang package public interface Comparable { public int compareTo(Object o); }
23
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; }
24
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.
25
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.
26
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.
27
// ShowInnerClass.java: Demonstrate using inner classes public 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(); }
28
Initialization Block Initialization 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.
29
Initialization Block public class Book { { numOfObjects++; }
30
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.
31
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"); }
32
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); }
33
== 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.
34
A Rectangle Class public 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; }
35
equals() example public 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); }
36
equals() example: result public 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)); //false System.out.println("rect1.equals(rect2): " + rect1.equals(rect2)); //true 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)); //true System.out.println("rect1.equals(rect2): " + rect1.equals(rect2)); //true int x = 12; int y = 12; System.out.println("x == y: " + (x == y) ); //true x = 5; y = x; x = 10; System.out.println("x == y: " + (x == y) ); //false System.out.println("x value: " + x + "\ty value: " + y); }
37
Equality versus Identity §confusion over equality and identity §identity: two things are in fact the same thing §equality: two things are for all practical purposes alike, but not the exact same thing §== versus the.equals method l use the equals method when you want to check the contents of the pointee, use == when you want to check memory addresses
38
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. l 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
39
Exceptions §Many languages, including Java use a mechanism know as Exceptions to handle errors at runtime l In Java Exception is a class with many descendants. l ArrayIndexOutOfBoundsException l NullPointerException l FileNotFoundException l ArithmeticException l IllegalArgumentException
40
Unchecked Exceptions §Exceptions in Java fall into two different categories l checked and unchecked §unchecked exceptions are completely preventable and should never occur. (They are caused by logic errors, created by us, the programmers.) l Descendents of the RuntimeException class l Examples: ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticException l There does not need to be special error handling code l 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
41
Checked Exceptions §Checked 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!
42
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 does not need to be placed in a try-catch block, but if an unchecked exception occurs and is not caught the program will stop
43
Dealing with exceptions §if a method has code that could generate a checked exception it must either l deal with it or l 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;}
44
When an Exception Occurs §If an exception occurs flow of control is shifted out of the try block or method where it occurred §The skipped code is not executed a 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
45
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 file return false; } finally {if(input != null) input.close(); }
46
Threads Concept Multiple threads on multiple CPUs Multiple threads sharing a single CPU
47
Creating Threads by Extending the Thread class
48
Using the Thread Class to Create and Launch Threads §Objective: Create and run three threads: l The first thread prints the letter a 100 times. l The second thread prints the letter b 100 times. l The third thread prints the integers 1 through 100.
49
Example 1: Using the Thread Class to Create and Launch Threads, cont. TestThread Run
50
Creating Threads by Implementing the Runnable Interface
51
Example 2: Using the Runnable Interface to Create and Launch Threads §Objective: Create and run three threads: l The first thread prints the letter a 100 times. l The second thread prints the letter b 100 times. l The third thread prints the integers 1 through 100. TestRunnable Run
52
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.
53
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.
54
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
55
Thread States
56
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");
57
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());
58
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.
59
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.
60
Example 3, cont PiggyBankWithoutSyncRun... }
61
Creating a Thread to run the while loop, cont. public void run() { while (true) { repaint(); try { thread.sleep(1000); waitForNotificationToResume(); } catch (InterruptedException ex) { }
62
Creating a Thread to run the while loop, cont. private synchronized void waitForNotificationToResume() throws InterruptedException { while (suspended) wait(); }
63
Creating a Thread to run the while loop, cont. public synchronized void resume() { if (suspended) { suspended = false; notify(); } public synchronized void suspend() { suspended = true; }
64
Example 4: Displaying a Running Clock in in an Applet Objective: Simulate a running clock by using a separate thread to repaint the clock. ClockAppletRun Applet Viewer
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.