1 / 41

Introduction to the Java Programming Language - Part 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 G. Fox and B. Carpenter in Florida State University. Last Class(1/2). Class

tavita
Download Presentation

Introduction to the Java Programming Language - Part 4 -

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 G. Fox and B. Carpenter in Florida State University

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

  3. Last Class(2/2) • Method public : public은 다른 클래스에서 자유롭게 접근할 수 있다. protected : protected 멤버 필드 혹은 메소드는 같은 패키지의 클래스들에서 접근할 수 있고, 또 다른 패키지일지라도 자식 클래스에서 접근할 수 있다. private : 자기 클래스 내부에서만 접근할 수 있다. 위의 제한자가 없는 경우(기본 제한 혹은 패키지 제한): 같은 패키지 안의 클래스에서만 접근 가능하다. 따라서, 접근 제한이 엄격한 정도를 표시하면 다음과 같다. public < protected < 기본(패키지) < private final(method와 field의 경우가 뜻이 다름) : 메소드의 경우에는 클래스를 상속할 때 오버라이드할 수 없는 메소드이다. 필드인 경우에는 수정이 불가능하다. static : 클래스 자체 수준의 필드 혹은 메소드임을 나타낸다. 이 경우, 해당 클래스의 모든 인스턴스에서 이를 공유하며 접근 시엔 '클래스 이름'.'메소드 혹은 필드 이름'을 사용한다.

  4. How to setup(1/5) • JDK & Kawa • JDK is in http://sun.co.kr • Kawa is in BBS

  5. How to Setup(2/5)

  6. How to Setup(3/5)

  7. How to Setup(4/5)

  8. How to Setup(5/5)

  9. Exceptions

  10. 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!

  11. 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 abreak statement; it causes the enclosing block of code to end abruptly. • If the throw statement appears inside a try statementwho’s catch clausematches 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).

  12. try { . . . throw new MyException() ; . . . } catch (MyException e) { . . . } . . . Control jumps to start of matching catch clause throw compared with break • myBlock : { • . . . • break myBlock ; • . . . • } • . . . • Control jumps to end of matching block

  13. 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 isnot enclosed by a matching try-catch construct, must bedeclared 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.

  14. 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 }

  15. Example using java.io import java.io.* ; PrintWriter out ; try { out = new PrintWriter(new FileOutputString(“filename”)) ; // create and open 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) ; }

  16. 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. . .

  17. 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

  18. 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, NullPointerException, 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.

  19. 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.

  20. Interfaces

  21. 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 superclass 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 abstract. • 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.

  22. 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 cannotinclude instance variables, constructors, or static methods. • They can include class variables, but only if they are declared final—essentially constant definitions.

  23. 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 . . . } }

  24. 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 class must be declared abstract. • Example: a class that defines the behaviour of a new thread must implement the Runnableinterface: 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.

  25. 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); } }

  26. 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 implementationsand 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.

  27. Interfaces can Extend other Interfaces • An interface can extendone or moreother interfaces: interface Material extends Storable, Paintable { // Additional methods if necessary. . . . . . } • If non-trivial “lattices” of types are really needed, eg: NoColor Red Blue Green Magenta Yellow Cyan AnyColor they can be implemented using interface types.

  28. 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 related 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 implementsuch an interface, just so it can access the included constants without using the Direction prefix.

  29. 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 invoked on an object from a subclass that does not implement the empty Cloneableinterface. • 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 Remoteinterface.

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

  31. Packages

  32. 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;

  33. 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 Stone { …} … Package mill ; Public class Wheat { …} …

  34. 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

  35. 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.

  36. Import statements • The import declaration allows you to avoid giving fully qualified names, 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.

  37. CLASSPATH • The import declaration only controls conventions on naming 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.

  38. 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 java.lang. Date is here as are Vector, hashtables, etc. • java.net contains classes to do network applications. Sockets, Internet addresses, URLs etc. • java.applet has the classes needed to support applets • java.awt has the original classes to support windowing—The Abstract Windows Toolkit. • java.awt.image has image processing classes.

  39. Java System Packages, II • java.awt.datatransfer contains classes to transfer data from a Java program 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 forRemote Method Invocation. • java.security enables a Java program to encrypt data and control the access privileges provided. • java.sql—Java Database Connectivity (JDBC) enables Java programs to interact with a database using the SQL language. • java.text are classes that provide internationalization capabilities for numbers, dates, characters and strings. • java.util.jar combines java .class files and other files into one compressed file called a Java archive (JAR) file.

  40. 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, tree, undo • org.omg.CORBA—Provides the mapping of the Object Management 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).

  41. 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.

More Related