⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 http:^^www.cs.wisc.edu^~cs537-1^java-tutorial.html

📁 This data set contains WWW-pages collected from computer science departments of various universities
💻 HTML
📖 第 1 页 / 共 5 页
字号:
<pre><font color="0f0fff">    interface Runnable {        public void run();    }    interface Enumeration {        public boolean hasMoreElements();        public Object nextElement();    }</font></pre>An object is <samp><font color="0f0fff">Runnable</font></samp> if it has a method named <samp><font color="0f0fff">run</font></samp> thatis public and has no arguments or results.To be an <samp><font color="0f0fff">Enumeration</font></samp>, it has to have a public member<samp><font color="0f0fff">hasMoreElements</font></samp>that returns a <samp><font color="0f0fff">boolean</font></samp> and a public member <samp><font color="0f0fff">nextElement</font></samp> thatreturns an <samp><font color="0f0fff">Object</font></samp>.A class that claims to <samp><font color="0f0fff">implement</font></samp> these interfaces has to eitherinherit them (via <samp><font color="0f0fff">extends</font></samp>) or define them itself.<pre><font color="0f0fff">    class Words extends StringTokenizer implements Enumeration, Runnable {        public void run() {            for (;;) {                String s = nextToken();                if (s == null) return;                System.out.println(s);            }        }        Words(String s) {            super(s);            // perhaps do something else with s as well        }    }</font></pre>The class <samp><font color="0f0fff">Words</font></samp> needs methods <samp><font color="0f0fff">run</font></samp>, <samp><font color="0f0fff">hasMoreElements</font></samp>, and<samp><font color="0f0fff">nextElement</font></samp> to meet its promise to implement interfaces<samp><font color="0f0fff">Runnable</font></samp> and <samp><font color="0f0fff">Enumeration</font></samp>.It inherits implementations of <samp><font color="0f0fff">hasMoreElements</font></samp> and<samp><font color="0f0fff">nextElement</font></samp> from<!WA19><!WA19><!WA19><!WA19><!WA19><!WA19><a href="http://www.cs.wisc.edu/~cs537-1/java/api/java.util.StringTokenizer.html"><samp><font color="0f0fff">StringTokenizer</font></samp> </a>, but it has to give its own implementation of <samp><font color="0f0fff">run</font></samp>.The <samp><font color="0f0fff">implements</font></samp> clause tells users of the class what they canexpect from it.If <samp><font color="0f0fff">w</font></samp> is an instance of <samp><font color="0f0fff">Words</font></samp>, I know I can write<samp><font color="0f0fff">w.run();</font></samp> or <samp><font color="0f0fff">if (w.hasMoreElements()) then ...</font></samp>.A class can only extend one class, but it can implement any number ofinterfaces.<p>By the way, constructors are not inherited.The call <samp><font color="0f0fff">super(s)</font></samp> in class <samp><font color="0f0fff">Words</font></samp> calls the constructor of<samp><font color="0f0fff">StringTokenizer</font></samp> that takes one <samp><font color="0f0fff">String</font></samp> argument.If you don't explicitly call <samp><font color="0f0fff">super</font></samp>, Java automatically callsthe super class constructor with no arguments (such a constructormust exist in this case).Note the call <samp><font color="0f0fff">nextToken()</font></samp> in <samp><font color="0f0fff">Words.run</font></samp>, which is short for<samp><font color="0f0fff">this.nextToken()</font></samp>.  Since <samp><font color="0f0fff">this</font></samp> is an instance of <samp><font color="0f0fff">Words</font></samp>,it has a <samp><font color="0f0fff">nextToken</font></samp> method -- the one it inherited from<samp><font color="0f0fff">StringTokenizer</font></samp>.<p>A <em>cast</em> in Java looks just like a cast in C++:  It is a typename in parentheses preceding an expression.We have<!WA20><!WA20><!WA20><!WA20><!WA20><!WA20><a href="#sort">already seen</a>an example of a cast used to convert between primitive types.A cast can also be used to convert an object reference to a super classor subclass.For example,<pre><font color="0f0fff">    Words w = new Words(&quot;this is a test&quot;);    Object o = w.nextElement();    String s = (String)o;    System.out.println(&quot;The first word has length &quot; + s.length());</font></pre>We know that <samp><font color="0f0fff">w.nextElement()</font></samp> is ok, since <samp><font color="0f0fff">Words</font></samp> implementsthe interface <samp><font color="0f0fff">Enumeration</font></samp>, but all that tells us is that the valuereturned has type <samp><font color="0f0fff">Object</font></samp>.We cannot call <samp><font color="0f0fff">o.length()</font></samp> because class <samp><font color="0f0fff">Object</font></samp> does nothave a <samp><font color="0f0fff">length</font></samp> method.In this case, however, we know that <samp><font color="0f0fff">o</font></samp> is not just any kind of<samp><font color="0f0fff">Object</font></samp>, but a <samp><font color="0f0fff">String</font></samp> in particular.Thus we <em>cast</em> <samp><font color="0f0fff">o</font></samp> to type <samp><font color="0f0fff">String</font></samp>.If we were wrong about the type of <samp><font color="0f0fff">o</font></samp> we would get a run-time error.If you are not sure of the type of an object, you can test itwith <samp><font color="0f0fff">instanceof</font></samp> (note the lower case `o'), or find out moreabout it with the method <samp><font color="0f0fff">Object.getClass()</font></samp><pre><font color="0f0fff">    if (o instanceof String)        n = ((String)o).length();    else        System.err.println(&quot;Bad type &quot; + o.getClass().getName());</font></pre><a name="exceptions"><h2> Exceptions </h2></a><p>A Java program should never ``core dump,'' no matter how buggy it is.If the compiler excepts it and something goes wrong at run time, Javathrows an <em>exception</em>.By default, an exception causes the program to terminate with an errormessage, but you can also <em>catch</em> an exception.<pre><font color="0f0fff">    try {        // ...        foo.bar();        // ...        a[i] = 17;        // ...    }    catch (IndexOutOfBoundsException e) {        System.err.println(&quot;Oops: &quot; + e);    }</font></pre>The <samp><font color="0f0fff">try</font></samp> statement says you're interested in catching exceptions.The <samp><font color="0f0fff">catch</font></samp> clause (which can only appear after a <samp><font color="0f0fff">try</font></samp>) says what todo if an <samp><font color="0f0fff">IndexOutOfBoundsException</font></samp> occurs anywhere in the<samp><font color="0f0fff">try</font></samp> clause.In this case, we print an error message.The <samp><font color="0f0fff">toString()</font></samp> method of an exception generates a string containinginformation about what went wrong, as well as a call trace.Because we caught this exception, it will not terminate the program.If some other kind of exception occurs (such as divide by zero),the exception will be thrown back to the caller of this function andif that function doesn't catch it, it will be thrown to that function'scaller, andso on back to the <samp><font color="0f0fff">main</font></samp> function, where it will terminate theprogram if it isn't caught.Similarly, if the function <samp><font color="0f0fff">foo.bar</font></samp> throws an<samp><font color="0f0fff">IndexOutOfBoundsException</font></samp> and doesn't catch it, we will catch it here.<p>The <samp><font color="0f0fff">catch</font></samp> clause actually catches <samp><font color="0f0fff">IndexOutOfBoundsException</font></samp>or any of its subclasses, including <samp><font color="0f0fff">ArrayIndexOutOfBoundsException</font></samp>,<samp><font color="0f0fff">StringIndexOutOfBoundsException</font></samp>, and others.An <samp><font color="0f0fff">Exception</font></samp> is just another kind of object, and the same rulesfor <!WA21><!WA21><!WA21><!WA21><!WA21><!WA21><a href="#inheritance">inheritance</a> hold for exceptions as anyother king of class.<p>You can define and throw your own exceptions.<pre><font color="0f0fff">    class SytaxError extends Exception {        int lineNumber;        SytaxError(String reason, int line) {            super(reason);            lineNumber = line;        }        public String toString() {            return &quot;Syntax error on line &quot; + lineNumber + &quot;: &quot; + getMessage();        }    }    class SomeOtherClass {        public void parse(String line) throws SyntaxError {            // ...            if (...)                throw new SyntaxError(&quot;missing comma&quot;, currentLine);            //...        }        public void parseFile(String fname) {            //...            try {                // ...                nextLine = in.readLine();                parse(nextLine);                // ...            }            catch (SyntaxError e) {                System.err.println(&quot;&quot; + e);            }        }    }</font></pre>Each function must declare in its header (with the keyword <samp><font color="0f0fff">throws</font></samp>)all the exceptions that may be thrown by it or any function it calls.It doesn't have to declare exceptions it catches.Some exceptions, such as <samp><font color="0f0fff">IndexOutOfBoundsException</font></samp>, are so common thatJava makes an exception for them(sorry about that) and doesn't require that they be declared.This rule applies to <samp><font color="0f0fff">RuntimeException</font></samp> and its subclasses.You should never define new subclasses of <samp><font color="0f0fff">RuntimeException</font></samp>.<p>There can be several <samp><font color="0f0fff">catch</font></samp> clauses at the end of a <samp><font color="0f0fff">try</font></samp>statement, to catch various kinds of exceptions.The first one that ``matches'' the exception (i.e., is a super class of it)is executed.You can also add a <samp><font color="0f0fff">finally</font></samp> clause, which will <em>always</em>be executed, no matter how the program leaves the <samp><font color="0f0fff">try</font></samp> clause(whether by falling through the bottom, executing a <samp><font color="0f0fff">return</font></samp>,<samp><font color="0f0fff">break</font></samp>, or <samp><font color="0f0fff">continue</font></samp>, or throwing an exception).<a name="threads"><h2> Threads </h2></a><p>Java lets you do several things at once by using <em>threads</em>.If your computer has more than one CPU, it may actually run two or more threadssimultaneously.Otherwise, it will switch back and forth among the threads at times thatare unpredictable unless you take special precautions to control it.<p>There are two different ways to create threads.  I will only describeone of them here.<pre><font color="0f0fff">    Thread t = new Thread(cmd); //     t.start();  // t start running cmd, but we don't wait for it to finish    // ... do something else (perhaps start other threads?)    // ... later:    t.join();  // wait for t to finish running cmd</font></pre>The constructor for the built-in class <samp><font color="0f0fff">Thread</font></samp> takes one argument, whichis any object that has a method called <samp><font color="0f0fff">run</font></samp>.This requirment is specified by requiringthat <samp><font color="0f0fff">command</font></samp> <em>implement</em> the<!WA22><!WA22><!WA22><!WA22><!WA22><!WA22><a href="#runnable"><samp><font color="0f0fff">Runnable</font></samp> </a> interface described earlier.The way a thread ``runs'' a command is simply by calling its <samp><font color="0f0fff">run()</font></samp>method.It's as simple as that!<p>In <!WA23><!WA23><!WA23><!WA23><!WA23><!WA23><a href="http://www.cs.wisc.edu/~cs537-1/project1.html">project 1</a>, you are supposed to run eachcommand in a separate thread.Thus you might declare something like this:<pre><font color="0f0fff">    class Command implements Runnable {        String theCommand;        Command(String c) {            theCommand = c;        }        public void run() {            // Do what the command says to do        }    }</font></pre>You can parse the command string either in the constructor or atthe start of the <samp><font color="0f0fff">run()</font></samp> method.<p>The main program loop reads a command line, breaks it up into commands,runs all of the commands concurrently (each in a separate thread),and waits for them to all finish before issuing the next prompt.In outline, it may look like this.<pre><font color="0f0fff">    for (;;) {        System.out.print(&quot;% &quot;); System.out.flush();        String line = inputStream.readLine();        int numberOfCommands = // count how many comands there are on the line        Thread t[] = new Thread[numberOfCommands];        for (int i=0; i&lt;numberOfCommands; i++) {            String c = // next command on the line            t[i] = new Thread(new Command(c));            t[i].start();        }        for (int i=0; i&lt;numberOfCommands; i++) {            t[i].join();        }    }</font></pre>This main loop is in the <samp><font color="0f0fff">main()</font></samp> method of your main class.It is not necessary for that class to implement <samp><font color="0f0fff">Runnable</font></samp>.<p>Although you won't need it for <!WA24><!WA24><!WA24><!WA24><!WA24><!WA24><a href="http://www.cs.wisc.edu/~cs537-1/project1.html">project 1</a>, the next project will requireto to synchronize thread with each other.There are two reasons why you need to do this:to prevent threads from interferring with each other, and to allowthem to cooperate.You use <samp><font color="0f0fff">synchronized</font></samp> methods to prevent interference, andthe built-in methods<samp><font color="0f0fff">Object.wait()</font></samp>,<samp><font color="0f0fff">Object.notify()</font></samp>,<samp><font color="0f0fff">Object.notifyAll()</font></samp>, and<samp><font color="0f0fff">Thread.yield()</font></samp>to support cooperation.<p>Any method can be preceded by the word <samp><font color="0f0fff">synchronized</font></samp> (aswell as <samp><font color="0f0fff">public</font></samp>, <samp><font color="0f0fff">static</font></samp>, etc.).The rule is:<p><center>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -