next up previous
Next: 1.6 The Visitor Pattern Up: 1.5 Loose Ends Previous: 1.5.3 Unchecked Exceptions

1.5.4 Static Type Checking

In Scheme every primitive operation dynamically checks that its arguments have the appropriate form (type) as it executes. If an operation is applied to data of the wrong form, Scheme aborts execution and prints an error message, much as Java does when an unchecked exception is thrown.

Java also performs some type checking at run-time, but most argument checking is done statically by the compiler before a Java program executes. A Java compiler must enforce a syntactic discipline on program text called static typing. The compiler uses a collection of type-checking rules to determine whether a program is ``well-typed'' or not. Programs that are not well-typed are rejected with an explanation of which rules were broken.

The type-checking rules generally embody simple common sense inference and consistency checking. In particular, given the invocation of a method m on an expression eof type T, T must be a class type including a method named m. Moreover, the types of any argument expression in the application must be subtypes (usually subclasses) of the declared types for the parameters of m. Applications of static methods are checked similarly.

There are only a few aspects of this type checking process that require further explanation. First, the type checking rules ignore the logical consequences of instanceof tests. Consider the following method which could inserted in the FunList class above.

static Object first(FunList l) {
  if (x instanceof Cons) return ((Cons) l).first;
  else 
    throw new ClassCastException("first requires a non-Empty Funlist"); 
}
In the method, all occurrences of the parameter l have the same type, namely FunList as declared in the method header. The instanceof Cons test has no effect on type-checking. As a result, the occurence of l preceding the field extraction operation .first must be cast to type Cons. The field .first is not defined in the abstract class FunList.

Applying a casting operation ( T ) to a Java expression e of some object type has two consequences. First, it inserts a run-time check to confirm that o belongs to the specified type T. Second, it converts the static type of the expression e to T.


next up previous
Next: 1.6 The Visitor Pattern Up: 1.5 Loose Ends Previous: 1.5.3 Unchecked Exceptions
Robert Cartwright, Spring 1999