41
Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hu n [email protected]. kr * This transparency is based on that made by G. Fox and B. Carpenter in Florida State University

Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun [email protected] * This transparency is based on that made by

Embed Size (px)

Citation preview

Page 1: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Introduction to the Java Programming Language

- Part 4 -

Instructor : An, Seung [email protected]

* This transparency is based on that made by G. Fox and B. Carpenter in Florida State University

Page 2: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Last Class(1/2)

• Class

public : 클래스에 대한 접근 제한자로 클래스 패키지 외부의 코드가 사용할 수 있는 클래스이다 . 하나의 소스 파일에는 최대 하나의 public 클래스만 허용되며 소스 파일의 이름은 반드시 이 클래스의 이름과 같아야 한다 .public 제한자가 없는 경우 ( 기본 접근 권한 혹은 패키지 권한 ): 현재 클래스와 동일한 패키지 내부에서 사용 가능한 클래스이다 . abstract : 추상 메소드 (abstract method- 실행문이 없는 메소드 ) 를 포함하거나 직접 실행되지 않는 클래스이다 . C++ 와 추상 클래스와 거의 같다 .final : C++ 에 없는 개념으로 자식 클래스를 만들 수 없는 클래스이다

Page 3: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Last Class(2/2)

• Method

public : public 은 다른 클래스에서 자유롭게 접근할 수 있다 .protected : protected 멤버 필드 혹은 메소드는 같은 패키지의 클래스들에서

접근할 수 있고 , 또 다른 패키지일지라도 자식 클래스에서 접근할 수 있다 .private : 자기 클래스 내부에서만 접근할 수 있다 .위의 제한자가 없는 경우 ( 기본 제한 혹은 패키지 제한 ): 같은 패키지 안의

클래스에서만 접근 가능하다 . 따라서 , 접근 제한이 엄격한 정도를 표시하면 다음과 같다 .

public < protected < 기본 ( 패키지 ) < private final(method 와 field 의 경우가 뜻이 다름 ) : 메소드의 경우에는 클래스를

상속할 때 오버라이드할 수 없는 메소드이다 . 필드인 경우에는 수정이 불가능하다 .

static : 클래스 자체 수준의 필드 혹은 메소드임을 나타낸다 . 이 경우 , 해당 클래스의 모든 인스턴스에서 이를 공유하며 접근 시엔 ' 클래스 이름 '.'메소드 혹은 필드 이름 ' 을 사용한다 .

Page 4: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

How to setup(1/5)

• JDK & Kawa– JDK is in http://sun.co.kr– Kawa is in BBS

Page 5: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

How to Setup(2/5)

Page 6: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

How to Setup(3/5)

Page 7: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

How to Setup(4/5)

Page 8: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

How to Setup(5/5)

Page 9: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

• Exceptions

Page 10: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Exceptions are Pervasive

• Java has a concept of exceptions similar to C++.

• Unlike C++, Java exceptions are strictly checked.

• Most classes in the standard Java library throw some exceptions. We will see, these must be caught or thrown.

• This means that it is almost impossible to write useful Java code without some knowledge of the exception mechanism!

Page 11: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Exception Objects, and throw

• Any kind of exception that can be thrown by Java code is described by an exception object. It’s class must be a subclass of Throwable.

• If e is a Throwable object, the statement

throw e ;

behaves something like a break statement; it causes the enclosing block of code to end abruptly.

• If the throw statement appears inside a try statement who’s catch clause matches the class of e, control is passed to the catch clause.

• Otherwise the whole method (or constructor) ends abruptly. The exception e is thrown again at the point of invocation (in the calling code).

Page 12: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

throw compared with break

try { . . . throw new MyException() ; . . .} catch (MyException e) { . . .}. . .

• Control jumps to start of matching catch clause

myBlock : { . . . break myBlock ; . . . } . . .

• Control jumps to end of matching block

Page 13: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Methods that throw exceptions

• In general, any exception that might be thrown in the body of a method or constructor, in a place where it is not enclosed by a matching try-catch construct, must be declared in a throws clause in the header of the method:

void foo() throws MyException { // throws clause . . . throw new MyException() ; // No enclosing // try- catch(MyException . . .) . . . }

• The compiler will insist invocations of foo() are treated with the same care as actual throw statements—either enclosed in matching try-catch constructs, or declared in turn in the header of the calling method.

Page 14: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Exception Handling in Nested Calls

void method1() { try { method2() ; } catch (Exception3 e) { doErrorProcessing(e); }}

void method2() throws Exception3 { method3() ; // method2 just passes exception through}

void method3 throws Exception3 { throw new Exception3() ; // create exception}

Page 15: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Example using java.io

import java.io.* ;

PrintWriter out ; try { out = new PrintWriter(new FileOutputString(“filename”)) ; // create and op

en file out.write(“stuff put out”) ; . . . out.close() ;

} catch (IOException e) { // Catches all I/O errors, including read and write stuff, say

System.err.println(“IO error: ” + e.getMessage()) ; System.exit(1) ;}

Page 16: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

How (not) to Ignore an Exception

• Sometimes you can’t think of a good way to recover from an exception—e.g. an exception thrown by a library method. But the compiler forces you to do something.

• Probably the worst thing you can do is to wrap the method invocation in a try-catch with an empty catch clause—

– the useless try-catch constructs make the code unreadable, and

– meanwhile, ignoring an error condition and silently carrying on the program may produce code even less reliable than, say, a typical C program, where the library error probably at least aborts the whole program!

• Usually it is safer to have your methods throw the exceptions—all the way up to the main method, if necessary. Then at least the program will stop.

• If you are really lazy you can just declare every method you ever write with throws Exception. . .

Page 17: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Part of the Exception Hierarchy

Throwable

...Error Exception

RuntimeException IOException

EOFException

FileNotFoundException

InterruptedIOException

• catch(FileNotFoundException e) { . . . } would catch specific exception whereas

• catch(IOException e) { . . . } would catch all IOexceptions

Page 18: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Unchecked Exceptions

• There are two exceptions (!) to the rule that all exceptions must be explicitly caught or thrown.

• Error classes usually represent problems that might occur unpredictably in the JVM. For example OutOfMemoryError (although unusual in practice) might occur at almost any time.

• RuntimeException classes usually represent errors “built into” the language—not thrown by a throw statement. There are about 20, including:– ArithmeticException, ArrayIndexOutOfBoundsException, NullP

ointerException, ClassCastException, etc.

• Note that exceptions that are thrown but not caught appear as error message on stderr. For applets they appear in the “Java console” of the browser.

Page 19: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Defining you own Exceptions• The Exception class has fields and methods to give information

how the exception occurred. There are two constructors; one includes a message in the instance.

• Can throw an exception of type Exception with a unique message, or create a subclass:class MyException extends Exception { public MyException () { super ("This is my exception message.") ; }}public static void MyMethod() throws MyException { . . . throw new MyException() ; . . . }

• Methods e.getMessage() and e.printStackTrace() can be used on exceptions.

Page 20: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

• Interfaces

Page 21: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Abstract Classes Revisited• Recall an abstract class is a class that contains some abstract

method declarations, with no implementation.• An abstract class can only be instantiated indirectly, as a supercl

ass of a class that overrides all the abstract methods, and gives them an implementation. You cannot directly create an instance of an abstract class.– Constructors, static methods, private methods cannot be abstract.– A subclass that does not override all abstract methods is still abstr

act.– A method that overrides a superclass method cannot be abstract

• But an abstract class will generally also contain “non-abstract” members—method implementations, instance variables, etc—and constructors.

Page 22: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Interfaces• An interface is something like an abstract class where

every method is required to be abstract.

• An interface specifies a collection of instance methods (behaviors) without giving the implementation of their bodies—akin to giving an API: public interface Storable { public abstract void store(Stream s) ; public abstract void retrieve(Stream s) ; }

• Interfaces cannot include instance variables, constructors, or static methods.

• They can include class variables, but only if they are declared final—essentially constant definitions.

Page 23: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Implementing an interface• As for an abstract class, one cannot directly create an

instance of an interface.• Unlike an abstract class, one cannot even extend an

interface to create a class. An interface is not a class, and it cannot have subclasses.

• Instead, a class must implement an interface:

public class Picture implements Storable { public void store(Stream s) { // JPEG compress image before storing . . . } public void retrieve(Stream s) { // JPEG decompress image after retrieving . . . } }

Page 24: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

An Interface is a Contract• Any class that implements an interface is guaranteeing a set of

behaviors. The body of the class will give concrete bodies to the methods in the interface.– If any methods in the interface are not implemented, the clas

s must be declared abstract.• Example: a class that defines the behaviour of a new thread mus

t implement the Runnable interface: public interface Runnable { public void run() ; }

• Any interface defines a type, similar to a class type. An instance of any class that implements a particular interface can be assigned to a variable with the associated interface type.

Page 25: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

An Interface Defines a Type

• Assume the classes Picture and StudentRecord both implement the Storable interface:public class StudentBody { Stream s; . . . public void register(Picture id_photo, StudentRecord id_card) { save(id_photo); save(id_card); } public void save(Storable o) { // o has type Storable o.store(s); } }

Page 26: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Classes can Implement Several Interfaces

• Interfaces address some of the same requirements as multiple inheritance in C++ (for example), but avoid various complexities and ambiguities that come from inheriting implementations and instance variables from multiple superclasses.

• A class can extend its superclass and implement several interfaces: class Picture implements Storable, Paintable {

// Body must now include any methods in Paintable, // as well as store() and retrieve().

. . . }

• Instances of the class acquire all the implemented interface types, in addition to inheriting their superclass type.

Page 27: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Interfaces can Extend other Interfaces

• An interface can extend one or more other interfaces: interface Material extends Storable, Paintable { // Additional methods if necessary. . . . . . }

• If non-trivial “lattices” of types are really needed, eg:

NoColor

GreenBlueRed

AnyColor

CyanYellowMagenta

they can be implemented using interface types.

Page 28: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Interfaces can hold Constant Definitions

• Interfaces can hold fields, provided are static and final.• An interface can be a natural place to define a collection of relat

ed constants, perhaps simulating a C-like enumeration type: public interface Direction { public final static int NORTH = 0 ; public final static int EAST = 1 ; public final static int SOUTH = 2 ; public final static int WEST = 4 ; }

• Use constants by, eg, Direction.NORTH.• Sometimes a class will implement such an interface, just so it c

an access the included constants without using the Direction prefix.

Page 29: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Interfaces can be used as Markers

• The Java environment includes several examples of empty interfaces that are used only as markers.

• By implementing such an interface, the programmer is typically telling the compiler or runtime system to treat the class in some special way:– Cloneable—the Object.clone() method will throw an exception if invo

ked on an object from a subclass that does not implement the empty Cloneable interface.

– Serializable—the ObjectOutputStream.writeObject() method will not write an object that does not implement the empty Serializable interface.

– Remote—any class whose methods may be invoked remotely using the RMI mechanism, must implement the empty Remote interface.

Page 30: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Summary

• Interfaces play a crucial role in structuring programs that need to declare multiple sets of behaviors such as applets and threads.

Page 31: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

• Packages

Page 32: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Packages

• One file can contain several related classes, but only one of them can be public. If the public class is called Wheat, then the file must be called Wheat.java.

• A set of classes in different files can be grouped together in a package. Each file must start with a package declaration, eg:

package mill;

Page 33: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Packages and Directory Structure (JDK)

• In JDK, each of the files in one package must be in the same directory (which may be in an jar archive file).

• For simple package names, the name of the directory should be the same as the package:

Directory name: mill

File: wheat.java: Stone.java:Package mill ;Public class Wheat { …}…

Package mill ;Public class Stone { …}…

Page 34: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Hierarchical Package Names

• Packages can be grouped hierarchically. For example, the mill package could be nested in a package called agriculture. Then the name of the package would be changed to agriculture.mill (full name required).

• In JDK, the classes of agriculture.mill should appear in a directory called: agriculture/mill (UNIX) agriculture\mill (Windows)

(relative to some directory, which must appear on the user’s CLASSPATH).

• Standard Java libraries are in packages with names like java.lang, java.util, java.io, etc.

• If you need to construct a globally unique name, can use your Internet domain name, inverted, as a prefix, eg: edu.fsu.csit.mpiJava

Page 35: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Fully Qualified Class Names

• A class can always be referred to in Java code by its fully qualified name which includes the package name as a prefix, eg: public class VectorTest { public static void main (String [] args) { java.util.Vector bag = new java.util.Vector() ; bag.addElement(new java.lang.String(“item”)) ; }

• Using fully qualified names is tedious in general.

Page 36: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Import statements• The import declaration allows you to avoid giving fully qualified n

ames, eg: import java.util.Vector ; // import declaration

public class VectorTest { public static void main (String [] args) { Vector bag = new Vector() ; bag.addElement(new String(“item”)) ; }

• Can also import all classes in, eg, java.util by import java.util.* ;

(but note wildcard can only appear in last position).• Note classes (like String) in java.lang are automatically imported.

Page 37: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

CLASSPATH• The import declaration only controls conventions on n

aming within a source file. It doesn’t address basic accessibility of the class files. You can use a class without importing it.

• In JDK (except for classes provided with the Java language) jar files or root directories of any package used (or class files for any classes not in any package) must be in the current directory, or in a directory in the CLASSPATH environment variable.

• This variable is used by both the compiler javac and the JVM command, java.

Page 38: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Java System Packages, I

• java.lang contains essential Java classes and is by default imported into every Java file. So import java.lang.* is unnecessary. For example Thread, Math, Object and wrapper classes are here.

• java.io contains classes to do I/O. • java.util contains various utility classes that didn't make it to jav

a.lang. Date is here as are Vector, hashtables, etc. • java.net contains classes to do network applications. Sockets, In

ternet addresses, URLs etc.• java.applet has the classes needed to support applets • java.awt has the original classes to support windowing—The Abs

tract Windows Toolkit.• java.awt.image has image processing classes.

Page 39: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Java System Packages, II• java.awt.datatransfer contains classes to transfer data from a Java pro

gram to the system clipboard (drag-and-drop).• java.beans contains classes to write reusable software components.• java.lang.reflect enables a program to discover the accessible variables

and methods of a class at run-time.• java.rmi—classes for Remote Method Invocation.• java.security enables a Java program to encrypt data and control the acc

ess privileges provided.• java.sql—Java Database Connectivity (JDBC) enables Java programs to i

nteract with a database using the SQL language.• java.text are classes that provide internationalization capabilities for nu

mbers, dates, characters and strings.• java.util.jar combines java .class files and other files into one compress

ed file called a Java archive (JAR) file.

Page 40: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Additional Java 1.2 System Packages

• javax.accessibility—contracts between user interface components and assistive technology.

• javax.swing—additional user interface components as well as providing standard “look and feel” for old ones.– border, colorchooser, event, filechooser, plaf, table, text, tre

e, undo• org.omg.CORBA—Provides the mapping of the Object Manageme

nt Group CORBA APIs to the Java programming language, including the class ORB, which is implemented so that a programmer can use it as a fully-functional Object Request Broker (ORB).

Page 41: Introduction to the Java Programming Language - Part 4 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Further information

• The Java 2 API specification: http://java.sun.com/products/jdk/1.2/docs/api

documentation in javadoc format.

• The Java Class Libraries, 2nd Edition, Volumes 1 and 2, plus supplements for the Java 2 platform.