Name and explain a reason why generics (such as generic packages in Ada or templates in C++) are a useful feature for a programming language to include.
Write the withdraw: method of our Account class so that the balance cannot drop below 0.
Say you want to add a unary instance method into Smalltalk's built-in Integer class called abs, which returns the absolute value of the Integer instance to which the method is applied. Write the definition of this method.
Name two significant and distinct differences between the object-oriented features of Java and Smalltalk. Do not address other differences, like their radically different syntax.
Consider the following Java program.
class A {
int f() { return 1; }
}
class B extends A {
int f() { return 0; }
}
class Main {
public static void main(String[] args) {
A a = new B();
System.out.println(a.f());
}
}
Consider the following program.
class Ident {
int f(int x) { return x; }
int g(int x) { return f(f(x)); }
}
class Square extends Ident {
int f(int x) { return x * x; }
}
class Main {
public static void main(String[] args) {
Ident a = new Ident();
Ident b = new Square();
Square c = new Square();
System.out.println(a.g(3) + " " + b.g(3) + " " + c.g(3));
}
}
Draw the Listener pattern using an UML Class Diagram.
(A more minor, but still legitimate, advantage is that generics allow the programmer to write a generic subprogram that takes a constant as a parameter, and this constant could be compiled into by the compiler into individual instances of the generic subprogram. For example, we could have a generic function that multiplies a number by a generic parameter.
generic
Mult : Integer
function Multiply(X : Integer) return Integer is
begin
return Mult * X;
end Multiply;
function Double is new Multiply(2);
function Triple is new Multiply(3);
The compiler will be able to optimize the Double routine to do
a left-shift instead of a multiplication.)
withdraw: aNumber
balance := balance - aNumber.
balance < 0
ifTrue: [ balance := 0 ]
abs
self >= 0 ifTrue: [ ^ self ] ifFalse: [ ^ 0 - self ]