Docsity

Java Interfaces and Inheritance: A Deep Dive - Prof. Alan L. Sussman, Study notes of Programming Languages

Toggle sidebar
bg1
1
CMSC433, Fall 2004
Programming Language Technology and
Paradigms
Java Review
Adam Porter
9/7/2004
2
Java
Descended from Simula67,
SmallTalk
, others
Superficially similar to C, C++
Fully specified, compiles to virtual machine
machine
-
independent
Secure
bytecode
verification (
type
-
safe
)
security manager
3
Object Orientation
Combining data and behavior
objects, not developers, decide how to carry out
operations
Sharing via abstraction and inheritance
similar operations and structures are implemented once
Emphasis on object
-
structure rather than
procedure structure
behavior more stable than implementation
but procedure structure still useful
4
Example
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
Using Complex
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
The Class Hierarchy
Classes by themselves are a powerful tool
Support
abstraction
and
encapsulation
Java also provides two other abilities
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
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Java Interfaces and Inheritance: A Deep Dive - Prof. Alan L. Sussman and more Study notes Programming Languages in PDF only on Docsity!

CMSC433, Fall 2004

Programming Language Technology and

Paradigms

Java Review

Adam Porter

2

Java

Descended from Simula67, SmallTalk, others

Superficially similar to C, C++

Fully specified, compiles to virtual machine

machine-independent

Secure

bytecode verification ( type-safe ) security manager

3

Object Orientation

Combining data and behavior

objects, not developers, decide how to carry out operations

Sharing via abstraction and inheritance

similar operations and structures are implemented once

Emphasis on object-structure rather than

procedure structure

behavior more stable than implementation but procedure structure still useful 4

Example

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

Using Complex

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

The Class Hierarchy

Classes by themselves are a powerful tool

Support abstraction and encapsulation

Java also provides two other abilities

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

Project 1: Interfaces

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

Interfaces

An interface lists supported (public) methods

No constructors or implementations allowed Can have final static variables

A class can implement (be a subtype of) zero or

more interfaces

Given some interface I , declaring I x = ... means

x must refer to an instance of a class that implements I , or else null

9

Interface Inheritance

Interfaces can extend other interfaces

Sometimes convenient form of reuse (see project 1)

Given interfaces I1 and I2 where I2 extends I

If C implements I2 , then C implements I

Since a class can implement multiple interfaces,

interface extensions are often not needed

10

Inheritance

Each Java class extends or inherits code from

exactly one superclass

Permits reusing classes to define new objects

Can define the behavior of the new object in terms of the old one

11

Example

class Point { int getX() { ... } int getY() { ... } } class ColorPoint extends Point { int getColor() { ... } }

ColorPoint reuses getX() and getY() from Point

ColorPoint implements the Point interface

They can be used anywhere a Point can be 12

Subtyping

Both inheritance and interfaces allow one class to

be used where another is specified

This is really the same idea: subtyping

We say that A is a subtype of B if

A extends B or a subtype of B , or A implements B or a subtype of B

19

I/O Classes

OutputStream byte stream going out

Writer character stream going out

InputStream byte stream coming in

Reader character stream coming in

20

Some OutputStreams and Writers

Example classes

ByteArrayOutputStream goes to byte [] FileOutputStream goes to file

OutputStreamWriter

wraps around OutputStream to get a Writer takes characters, converts to bytes can specify encoding used to convert

Other wrappers

PrintWriter supports print , println StringWriter

21

Applications and I/O

Java external interface is a public class

public static void main(String [] args)

args[0] is first argument

unlike C/C++

System.out and System.err are PrintStreams

should be PrintWriter , but would break 1.0 code System.out.print( ) prints a string System.out.println( ) prints a string with a newline

System.in is an InputStream

not quite so easy to use 22

Java Networking

class Socket

Communication channel

class ServerSocket

Server-side listen socket Awaits and responds to connection requests

23

Example Client/Server

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 code

server client

Client

code

24

Example Client/Server

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 code

server client

Client

code

25

Example Client/Server

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 code

server client

Client

code

26

Example Client/Server

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 code

server client

Note: The server can still accept other connection requests on port 5001

Client

code

27

Example Client/Server

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 code

server client

in out

Client

code

28

Example Client/Server

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 code

server client

in out

in out

Client

code

29

Possible Failures

Server-side

ServerSocket port already in use Client dies on accept

Client-side

Server dead No one listening on port

In all cases IOException thrown

Must use appropriate throw/try/catch constructs

30

Class Objects

For each class, there is an object of type Class

Describes the class as a whole

used extensively in Reflection package

Class.forName( MyClass )

returns class object for MyClass will load MyClass if needed

Class.forName( MyClass ).newInstance()

creates a new instance of MyClass

MyClass.class gives the Class object for MyClass

37

Example: Mutability

a[1] = 0; // also changes b[1]

Moral: Always be

careful when you have

aliasing

Multiple references to the same object

38

Method Invocation

Syntax

o.m(arg1, arg2, ..., argn);

Run the m method of object o with arguments arg1...argn

Two ways to reuse method names:

Methods can be overridden Methods can be overloaded

39

Overriding

Define a method also defined by a superclass

class Parent { int cost; void add(int x) { cost += x; } }

class Child extends Parent { void add(int x) { if (x > 0) cost += x; } }

40

Overriding (cont d)

Method with same name and argument types in

child class overrides method in parent class

Arguments and result types must be identical

otherwise you are overloading the method

Must raise the same or fewer exceptions

Can override/hide instance variables

both variables will exist, but don t do it

41

Declared vs. Actual Types

The actual type of an object is its allocated type

Integer o = new Integer(1);

A declared type is a type at which an object is

being viewed

Object o = new Integer(1); void m(Object o) { ... }

Each object always has one actual type, but can

have many declared types

42

Method Dispatch

Consider again

o.m(arg1, arg2, ..., argn);

Only compiles if o s declared type contains an

appropriate m method

Method corresponding to o s actual type is what is

invoked

43

Dynamic Dispatch Example

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()); } }

Prints I m a B! I m a B!

44

Self Reference

this refers to the object the method is invoked on

Thus can access fields of this object as this.x or this.y But more concise to omit

super refers to the same object as this

But used to access methods/variables in superclass

45

Example of super

Call a superclass method from a subclass

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

Overloading

Methods with the same name, but different

parameters (count or types) are overloaded

Invocation determined by name and types of params Not return value or exceptions

Resolved at compile-time , based on declared types

Be careful: Easy to inadvertently overload instead

of override!

47

Overloading Example

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 and Methods

static stored with the class

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

Can reference class variables and methods through

either class name or an object ref

Clearer to reference via the class name

55

Other Method Modifiers

final this method cannot be overridden

Useful for security Allows compiler to inline method

abstract no implementation provided

Class must be abstract

public visible outside this package

native , synchronized

Will cover later

56

Poor man s polymorphism

Every object is a subtype of Object

Thus, a data structure Set that implements sets of

Objects

can also hold Strings or images or anything!

The trick is getting them back out:

When given an Object , you have to downcast it

57

Downcasting

(Bar) foo

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

o instanceof Foo returns true iff o is a subtype of

Foo

58

Example

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

Wrapper (Boxed) classes

Integer , Boolean , Double ,

Are subclasses of Object Useful/required for polymorphic methods HashTable , LinkedList , Used in reflection classes

Include many utility functions

For example, convert to/from String

60

Array types

Misfeature: suppose S is a subtype of T

then S[] is a subtype of T[]

Object[] is a supertype of all arrays of reference

types

61

Example: Object[]

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

Problem with Subtyping Arrays

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) }

Program compiles without warning

Java must generate run-time check at (1) to prevent (2)

Type written to array must be subtype of declared type

63

Project 1 Notes

Project 1 shows some of the issues in software

components

And a few design patterns as well (more later)

MiniServlet is the interface between components

WebServer shouldn t assume anything about MiniServlets it will run MiniServlets shouldn t assume anything about server that will invoke them

64

Multiple Vendors

65

Things to Check

If grep Proxy WebServer.java finds a match,

you likely have a problem

Can you put just WebServer.java and

MiniServlet.java in a directory and compile them?

Can you put everything except WebServer.java in

a directory and compile them all?

Can you use TestServlet to run your servlets?

66

Java Classes and Objects

Each object is an instance of a class

An array is an object

Each class extends one superclass

Object if not specified Class Object has no superclass

73

Signaling Errors

Style 1: Return invalid value

// Returns value key maps to, or null if no // such key in map Object get(Object key);

Disadvantages?

74

Signaling Errors (cont d)

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

Problems with These Approaches

What if all possible return values are valid?

E.g., findMax from earlier slide

What if client forgets to check for error?

No compiler support

What if client can t handle error?

Needs to be dealt with at a higher level

76

Exceptions in Java

On an error condition, we throw an exception

At some point up the call chain, the exception is

caught and the error is handled

Separates normal from error-handling code

A form of non-local control-flow

Like goto, but structured

77

Throwing an Exception

Create a new object of the class Exception , and

throw it

if (i >= 0 && i < a.length ) return a[i]; else throw new ArrayIndexOutOfBounds();

Exceptions thrown are part of return type

When overriding method in superclass, cannot throw any more exceptions than parent s version

78

Method throws declarations

A method declares the exceptions it might throw

public void openNext() throws UnknownHostException, EmptyStackException { }

Must declare any exception the method might throw

Unless it is caught in (masked by) the method Includes exceptions thrown by called methods Certain kinds of exceptions excluded

79

Exception Handling

All exceptions eventually get caught

First catch with supertype of the exception

catches it

finally is always executed

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

Masking Exceptions

Handle exception and continue

while ((s = ...) != null) { try { FileInputStream f = new FileInputStream(s); ... } catch (FileNotFoundException e) { System.out.println(s + not found ); } }

81

Reflecting Exceptions

Pass exception up to higher level

Automatic support for throwing same exception Sometimes useful to throw different exception

try { ... a[5] ... } catch (IndexOutOfBoundsException e) { throw new EmptyException( Arrays.min ); }

82

Exception Chaining

Indicate the cause of a thrown exception

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

Exception Hierarchy

Throwable

Error Exception

RuntimeException

Checked

Unchecked

84

Unchecked Exceptions

Subclasses of RuntimeException and Error are

unchecked

Need not be listed in method specifications

Currently used for things like

NullPointerException IndexOutOfBoundsException VirtualMachineError

Is this a good design?