









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










2
Superficially similar to C, C++
machine-independent
bytecode verification ( type-safe ) security manager
3
objects, not developers, decide how to carry out operations
similar operations and structures are implemented once
behavior more stable than implementation but procedure structure still useful 4
public class Complex { private double r, i;
public Complex(double r, double i) { this.r = r; this.i = i; } public String toString() { return ( + r + , + i + ) ; } public Complex plus(Complex that) { return new Complex(r + that.r, i + that.i); } }
5
public static void main(String[] args) { Complex a = new Complex(5.5,9.2); Complex b = new Complex(2.3,-5.1); Complex c; c = a.plus(b); System.out.println( a = + a); System.out.println( b = + b); System.out.println( c = + c); }
6
Support abstraction and encapsulation
Interfaces allow different classes to be treated the same Inheritance allows code reuse Note: When you inherit from a class, you also implement the class s interface
7
public interface MiniServlet extends Runnable { void setArg(String arg); void setOutputStream(OutputStream out); }
class HelloWorld implements MiniServlet { ... } class Print implements MiniServlet { ... }
MiniServlet s = new HelloWorld(); if (...) s = new Print(); s.setArg(...);
8
No constructors or implementations allowed Can have final static variables
x must refer to an instance of a class that implements I , or else null
9
Sometimes convenient form of reuse (see project 1)
If C implements I2 , then C implements I
10
Can define the behavior of the new object in terms of the old one
11
class Point { int getX() { ... } int getY() { ... } } class ColorPoint extends Point { int getColor() { ... } }
They can be used anywhere a Point can be 12
This is really the same idea: subtyping
A extends B or a subtype of B , or A implements B or a subtype of B
19
20
ByteArrayOutputStream goes to byte [] FileOutputStream goes to file
wraps around OutputStream to get a Writer takes characters, converts to bytes can specify encoding used to convert
PrintWriter supports print , println StringWriter
21
public static void main(String [] args)
unlike C/C++
should be PrintWriter , but would break 1.0 code System.out.print( ) prints a string System.out.println( ) prints a string with a newline
not quite so easy to use 22
Communication channel
Server-side listen socket Awaits and responds to connection requests
23
ServerSocket s = new ServerSocket(5001); Socket conn = s.accept(); InputStream in = conn.getInputStream(); OutputStream out = conn.getOutputStream();
Socket conn = new Socket ( www.cs.umd.edu , 5001); InputStream in = conn.getInputStream(); OutputStream out = conn.getOutputStream();
server client
24
ServerSocket s = new ServerSocket(5001); Socket conn = s.accept(); InputStream in = conn.getInputStream(); OutputStream out = conn.getOutputStream();
Socket conn = new Socket ( www.cs.umd.edu , 5001); InputStream in = conn.getInputStream(); OutputStream out = conn.getOutputStream();
server client
25
ServerSocket s = new ServerSocket(5001); Socket conn = s.accept(); InputStream in = conn.getInputStream(); OutputStream out = conn.getOutputStream();
Socket conn = new Socket ( www.cs.umd.edu , 5001); InputStream in = conn.getInputStream(); OutputStream out = conn.getOutputStream();
server client
26
ServerSocket s = new ServerSocket(5001); Socket conn = s.accept(); InputStream in = conn.getInputStream(); OutputStream out = conn.getOutputStream();
Socket conn = new Socket ( www.cs.umd.edu , 5001); InputStream in = conn.getInputStream(); OutputStream out = conn.getOutputStream();
server client
Note: The server can still accept other connection requests on port 5001
27
ServerSocket s = new ServerSocket(5001); Socket conn = s.accept(); InputStream in = conn.getInputStream(); OutputStream out = conn.getOutputStream();
Socket conn = new Socket ( www.cs.umd.edu , 5001); InputStream in = conn.getInputStream(); OutputStream out = conn.getOutputStream();
server client
in out
28
ServerSocket s = new ServerSocket(5001); Socket conn = s.accept(); InputStream in = conn.getInputStream(); OutputStream out = conn.getOutputStream();
Socket conn = new Socket ( www.cs.umd.edu , 5001); InputStream in = conn.getInputStream(); OutputStream out = conn.getOutputStream();
server client
in out
in out
29
ServerSocket port already in use Client dies on accept
Server dead No one listening on port
Must use appropriate throw/try/catch constructs
30
used extensively in Reflection package
returns class object for MyClass will load MyClass if needed
creates a new instance of MyClass
37
a[1] = 0; // also changes b[1]
Multiple references to the same object
38
o.m(arg1, arg2, ..., argn);
Run the m method of object o with arguments arg1...argn
Methods can be overridden Methods can be overloaded
39
class Parent { int cost; void add(int x) { cost += x; } }
class Child extends Parent { void add(int x) { if (x > 0) cost += x; } }
40
otherwise you are overloading the method
both variables will exist, but don t do it
41
Integer o = new Integer(1);
Object o = new Integer(1); void m(Object o) { ... }
42
o.m(arg1, arg2, ..., argn);
43
public class A { String f() { return I m an A! ; } }
public class B extends A { String f() { return I m a B! ; } public static void main(String args[]) { A a = new B(); B b = new B(); System.out.println(a.f() + b.f()); } }
44
Thus can access fields of this object as this.x or this.y But more concise to omit
But used to access methods/variables in superclass
45
class Parent { int cost; void add(int x) { cost += x; } }
class Child extends Parent { void add(int x) { if (x > 0) super.add(x); } }
46
Invocation determined by name and types of params Not return value or exceptions
47
class Parent { int cost; void add(int x) { cost += x; } void add(Object s) throws NumberFormatException { cost += Integer.parseInt((String)s); } } class Child extends Parent { void add(String s) throws NumberFormatException { if (x > 0) cost += Integer.parseInt(s); } } Child c = new Child(); c.add((Object) -1 ); System.out.println(c.cost);
Prints -
48
Static fields allocated once, no matter how many objects created Static methods are not specific to any class instance, so cannot refer to this or super
Clearer to reference via the class name
55
Useful for security Allows compiler to inline method
Class must be abstract
Will cover later
56
can also hold Strings or images or anything!
When given an Object , you have to downcast it
57
Run-time exception if object reference by foo is not a subtype of Bar Compile-time error if Bar is not a subtype of foo (i.e., it always throws an exception) No effect at run-time; just treats the result as if it were of type Bar
58
class DumbSet { public void insert(Object o) {..} public bool member(Object o) {..} public Object any() {..} }
class MyProgram { public static void main(String[] args) { DumbSet set = new DumbSet(); String s1 = foo ; String s2 = bar ; set.insert(s1); set.insert(s2); System.out.println(s1+ in set? +set.member(s1)); String s = (String)set.any(); // downcast System.out.println( got +s); } }
59
Are subclasses of Object Useful/required for polymorphic methods HashTable , LinkedList , Used in reflection classes
For example, convert to/from String
60
then S[] is a subtype of T[]
61
public class TestArrayTypes { public static void reverseArray(Object [] A) { for(int i=0, j=A.length-1; i<j; i++,j--) { Object tmp = A[i]; A[i] = A[j]; A[j] = tmp; } } public static void main(String [] args) { reverseArray(args); for(int i=0; i < A.length; i++) System.out.println(args[i]); } }
62
public class A { ... } public class B extends A { void newMethod(); } ... void foo(void) { B[] bs = new B[]; A[] as;
5.27// Since B[] subtype of A[] as[0] = new A(); // (1) bs[0].newMethod(); // (2) }
Type written to array must be subtype of declared type
63
And a few design patterns as well (more later)
WebServer shouldn t assume anything about MiniServlets it will run MiniServlets shouldn t assume anything about server that will invoke them
64
65
66
An array is an object
Object if not specified Class Object has no superclass
73
// Returns value key maps to, or null if no // such key in map Object get(Object key);
Disadvantages?
74
Style 2: Return an invalid value and status *static int lock_rdev(mdk_rdev_t rdev) { ... if (bdev == NULL) return -ENOMEM; ... }
**// Returns NULL if error and sets global // variable errno FILE *fopen(const char path, const char mode);
75
E.g., findMax from earlier slide
No compiler support
Needs to be dealt with at a higher level
76
Like goto, but structured
77
if (i >= 0 && i < a.length ) return a[i]; else throw new ArrayIndexOutOfBounds();
When overriding method in superclass, cannot throw any more exceptions than parent s version
78
public void openNext() throws UnknownHostException, EmptyStackException { }
Unless it is caught in (masked by) the method Includes exceptions thrown by called methods Certain kinds of exceptions excluded
79
try { if (i == 0) return; myMethod(a[i]); } catch (ArrayIndexOutOfBounds e) { System.out.println( a[] out of bounds ); } catch (MyOwnException e) { System.out.println( Caught my error ); } catch (Exception e) { System.out.println( Caught + e.toString()); throw e; } finally { /* stuff to do regardless of whether an exception / / was thrown or a return taken */ } 80
while ((s = ...) != null) { try { FileInputStream f = new FileInputStream(s); ... } catch (FileNotFoundException e) { System.out.println(s + not found ); } }
81
Automatic support for throwing same exception Sometimes useful to throw different exception
try { ... a[5] ... } catch (IndexOutOfBoundsException e) { throw new EmptyException( Arrays.min ); }
82
Specify the exception that caused this one Shows cause chain in stack trace
try { ... a[0] ... } catch (IndexOutOfBoundsException e) { // e can be retrieved from exn with getCause() throw new Exception( Arrays.min , e); }
83
Throwable
Error Exception
RuntimeException
Checked
Unchecked
84
Need not be listed in method specifications
NullPointerException IndexOutOfBoundsException VirtualMachineError