📄 http:^^www.cs.wisc.edu^~cs537-1^java-tutorial.html
字号:
public: int j; void f() { /*...*/ } }</font></pre>In Java:<pre><font color="0f0fff"> class C { private int i; public int j; private double d; public void f() { /* ... */ } }</font></pre>As in C++, private members can only be accessed from inside the bodiesof methods (function members) of the class, not ``from the outside.''Thus if <samp><font color="0f0fff">x</font></samp> is an instance of <samp><font color="0f0fff">C</font></samp>, <samp><font color="0f0fff">x.i</font></samp> is not legal,but <samp><font color="0f0fff">i</font></samp> can be accessed from the body of <samp><font color="0f0fff">x.f()</font></samp>.(<samp><font color="0f0fff">protected</font></samp> is also supported; it means the same thing as it doesin C++).The default (if neither <samp><font color="0f0fff">public</font></samp> nor <samp><font color="0f0fff">private</font></samp> is specified)is that a member can be accessed from anywhere in the same <em>package</em>,giving a facility rather like ``friends'' in C++.You will probably be putting all your classes in one package, sothe default is essentially <samp><font color="0f0fff">public</font></samp>.<p>The keyword <samp><font color="0f0fff">static</font></samp> also means the same thing in Java as C++,which not what the word implies:Ordinary members have one copy per instance, while <samp><font color="0f0fff">static</font></samp> membershave only one copy, shared by instances.In effect, a <samp><font color="0f0fff">static</font></samp> member lives in the class itself, rather thaninstances.<pre><font color="0f0fff"> class C { int x = 1; // by the way, this isn't legal in C++ static int y = 1; void f(int n) { x += n; } static int g() { return ++y; } } C p = new C(); C q = new C(); p.f(3); q.f(5); System.out.println(p.x); // prints 4 System.out.println(q.x); // prints 6 System.out.println(C.y); // prints 1 System.out.println(p.y); // means the same thing System.out.println(C.g());// prints 2 System.out.println(q.g());// prints 3</font></pre>Static members are often used instead of global variables and functions,which do not exist in Java.For example,<pre><font color="0f0fff"> Math.tan(x); // tan is a static method of class Math Math.PI; // a static "field" of class Math Integer.parseInt("10"); // used <a href="#sort">in the sorting example</a></font></pre>The keyword <samp><font color="0f0fff">final</font></samp> is roughly equivalent to <samp><font color="0f0fff">const</font></samp> in C++:<samp><font color="0f0fff">final</font></samp> fields cannot be changed.It is often used in conjunction with <samp><font color="0f0fff">static</font></samp> to defined named constants.<pre><font color="0f0fff"> class Card { int suit = CLUBS; // default final static int CLUBS = 1; final static int DIAMONDS = 2; final static int HEARTS = 3; final static int SPADES = 4; } Card c = new Card(); c.suit = Card.SPADES;</font></pre>Each <samp><font color="0f0fff">Card</font></samp> has its own suit.The value <samp><font color="0f0fff">CLUBS</font></samp> is shared by all instances of <samp><font color="0f0fff">Card</font></samp> soit only needs to be stored once, but since it's <samp><font color="0f0fff">final</font></samp>, it doesn'tneed to be stored at all!<a name="arrays"><h2> Arrays </h2></a><p>In Java, arrays are objects.Like all objects in Java, you can only point to them, but unlike a C++variable, which is treated like a pointer to the first elementof the array, a Java array variable points to the array object.There is no way to point to a particular member of an array.<p>Each array has a read-only (final) field <samp><font color="0f0fff">length</font></samp> that tells you howmany elements it has. The elements are numbered starting at zero as in C++:<samp><font color="0f0fff">a[0] ... a[a.length-1]</font></samp>.Once you create an array (using <samp><font color="0f0fff">new</font></samp>), you can't change its size.If you need more space, you have to create a new (larger) array and copyover the elements (but see the library class<a htref="#vectors"><samp><font color="0f0fff">Vector</font></samp></a>below).<pre><font color="0f0fff"> int x = 3; // a value int a[]; // a pointer to an array object; initially null int[] a; // means exactly the same thing a = new int[10]; // now a points to an array object a[3] = 17; // accesses one of the slots in the array a = new int[5]; // assigns a different array to a // the old array is inaccessible (and so // is garbage-collected) int[] b = a; // a and b share the same array object System.out.println(a.length); // prints 5</font></pre><center><!WA18><!WA18><!WA18><!WA18><!WA18><!WA18><IMG ALIGN=TOP SRC="http://www.cs.wisc.edu/~cs537-1/arrays.gif">.</center><a name="strings"><h2> Strings </h2></a><p>Since you can make an array of anything, you can make an an array of<samp><font color="0f0fff">char</font></samp> or an an array of <samp><font color="0f0fff">byte</font></samp>, but Java has something much better:the type <samp><font color="0f0fff">String</font></samp>.The <samp><font color="0f0fff">+</font></samp> operator is <em>overloaded</em> on Strings to meanconcatenation. What's more, you can concatenate <em>anything</em> witha string; Java automatically converts it to a string.Built-in types such as numbers are converted in the obvious way.Objects are converted by calling their <samp><font color="0f0fff">toString()</font></samp> methods.Library classes all have <samp><font color="0f0fff">toString</font></samp> methods that do something reasonable.You can do likewise for classes you define.This is great for debugging.<pre><font color="0f0fff"> String s = "hello"; String t = "world"; System.out.println(s + ", " + t); // prints "hello, world" System.out.println(s + "1234"); // "hello1234" System.out.println(s + (12*100 + 34)); // "hello1234" System.out.println(s + 12*100 + 34); // "hello120034" (why?) System.out.println("The value of x is " + x); // will work for any x System.out.println("System.out = " + System.out); // "System.out = java.io.PrintStream@80455198" String numbers = ""; for (int i=0; i<5; i++) numbers += " " + i; System.out.println(numbers); // " 1 2 3 4 5"</font></pre>Strings have lots of other useful operations:<pre><font color="0f0fff"> String s = "whatever", t = "whatnow"; s.charAt(0); // 'w' s.charAt(3); // 't' t.substring(4); // "now" t.substring(4,6); // "no" s.substring(0,4); // "what" t.substring(0,4); // "what" s.compareTo(t); // a value less than zero (s precedes t in "lexicographic" // (dictionary) order t.compareTo(s); // a value greater than zero (t follows s) t.compareTo("whatnow"); // zero t.substring(0,4) == s.substring(0,4); // false (they are different String objects) t.substring(0,4).equals(s.substring(0,4)); // true (but they are both equal to "what") t.indexOf('w'); // 0 t.indexOf('t'); // 3 t.indexOf("now"); // 4 t.lastIndexOf('w'); // 6 t.endsWith("now"); // true</font></pre>and more.<p>You can't modify a string, but you can make a string variable point toa new string (as in <samp><font color="0f0fff">numbers += " " + i;</font></samp>). See <samp><font color="0f0fff">StringBuffer</font></samp> ifyou want a string you can scribble on.<a name="constructors"><h2> Constructors and Overloading </h2></a><p>A constructor is like in C++: a method with the same name as the class.If a constructor has arguments, you supply corresponding values when using<samp><font color="0f0fff">new</font></samp>. Even if it has no arguments, you still need the parentheses(unlike C++).There can be multiple constructors, with different numbers or types ofarguments. The same is true for other methods. This is called<em>overloading</em>. Unlike C++, you cannot overload operators.The operator `+' is overloaded for strings and (various kinds of) numbers,but user-defined overloading is not allowed.<pre><font color="0f0fff"> class Point { int x, y; Point(int u, int v) { x = u; // the same as this.x = u y = v; } Point(int x) { this.x = x; // not the same as x = x! y = 0; } Point() { x = 0; y = 0; } } class Test { public static void main(String[] argv) { Point p1 = new Point(3,4); Point p2 = new Point(); // same as new Point(0,0) Point p3 = new Point; // error! } }</font></pre><strong>NB:</strong> The bodies of the methods have to be defined<em>in line</em> right after their headers as shown above. You have towrite<pre><font color="0f0fff"> class Foo { double square(double d) { return d*d; } };</font></pre>rather than<pre><font color="0f0fff"> class Foo { double square(double); }; double Foo::square(double d) { return d*d; } // ok in C++ but not in Java</font></pre> <a name="inheritance"><h2> Inheritance, Interfaces, and Casts </h2></a><p>In C++, when we write<pre><font color="0f0fff"> class Derived : public Base { ... }</font></pre>we mean two things:<ul><li> A <samp><font color="0f0fff">Derived</font></samp> can do anything a <samp><font color="0f0fff">Base</font></samp> can, and perhaps more.<li> A <samp><font color="0f0fff">Derived</font></samp> does things the way a <samp><font color="0f0fff">Base</font></samp> does them,unless specified otherwise.</ul>The first of these is called <em>interface inheritance</em> or<em>subtyping</em> and the secondis called <em>method inheritance</em>.In Java, they are specified differently.<p>Method inheritance is specified with the keyword <samp><font color="0f0fff">extends</font></samp>.<pre><font color="0f0fff"> class Base { int f() { /* ... */ } void g(int x) { /* ... */ } } class Derived extends Base { void g(int x) { /* ... */ } double h() { /* ... */ } }</font></pre>Class <samp><font color="0f0fff">Derived</font></samp> has three methods: <samp><font color="0f0fff">f</font></samp>, <samp><font color="0f0fff">g</font></samp>, and <samp><font color="0f0fff">h</font></samp>. Themethod <samp><font color="0f0fff">Derived.f()</font></samp> is implemented in the same way (the same executablecode) as <samp><font color="0f0fff">Base.f()</font></samp>, but <samp><font color="0f0fff">Derived.g()</font></samp> <em>overrides</em> theimplementation of <samp><font color="0f0fff">Base.g()</font></samp>.We call <samp><font color="0f0fff">Base</font></samp> the <em>super class</em> of <samp><font color="0f0fff">Derived</font></samp> and<samp><font color="0f0fff">Derived</font></samp> a <em>subclass</em> of <samp><font color="0f0fff">Base</font></samp>.Every class (with one exception) has exactly one super class (singleinheritance). If you leave out the <samp><font color="0f0fff">extends</font></samp> specification, Javatreats it like ``<samp><font color="0f0fff">extends Object</font></samp>''.The primordial class<samp><font color="0f0fff">Object</font></samp> is the lone exception -- it does not extend anything. All other classes extend <samp><font color="0f0fff">Object</font></samp> either directly or indirectly.<samp><font color="0f0fff">Object</font></samp> has a method <samp><font color="0f0fff">toString</font></samp>, so every class has a method<samp><font color="0f0fff">toString</font></samp>; either it inherits the method from its super classor it overrides it.<p>Interface inheritance is specified with <samp><font color="0f0fff">implements</font></samp>.A class implements an <em>Interface</em>, which is like a class, except thatthe methods don't have bodies.Two examples are given by the built-in interfaces<a name="runnable"><samp><font color="0f0fff">Runnable</font></samp></a>and<samp><font color="0f0fff">DataInput</font></samp>.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -