Concepts of Programming Languages

(Sean Pound) #1

552 Chapter 12 Support for Object-Oriented Programming


shapteRef = myCircle;
[shapeRef draw];

// Set the id to reference the square
shapeRef = mySquare;
[shapeRef draw];

This code first draws the circle and then the square, with both draw methods
called through the shapeRef object reference.

12.6.4 Evaluation


The support for object-oriented programming in Objective-C is adequate,
although there are a few minor deficiencies. There is no way to prevent over-
riding of an inherited method. Support for polymorphism with its id data
type is overkill, for it allows variables to reference any object, rather than just
those in an inheritance line. Although there is no direct support for multiple
inheritance, the language includes a form of a mixin, categories, which provide
some of the capabilities of multiple inheritance, without all of its disadvantages.
Categories allow a collection of behaviors to be added to any class. Protocols
provide the capabilities of interfaces, such as those in Java, which also provide
some of the capabilities of multiple inheritance.

12.7 Support for Object-Oriented Programming in Java


Because Java’s design of classes, inheritance, and methods is similar to that of
C++, in this section we focus only on those areas in which Java differs from C++.

12.7.1 General Characteristics


As with C++, Java supports both objects and nonobject data. However, in Java,
only values of the primitive scalar types (Boolean, character, and the numeric
types) are not objects. Java’s enumerations and arrays are objects. The reason
to have nonobjects is efficiency.
In Java 5.0+, primitive values are implicitly coerced when they are put in
object context. This coercion converts the primitive value to an object of the
wrapper class of the primitive value’s type. For example, putting an int value
or variable into object context causes the creation of an Integer object with
the value of the int primitive. This coercion is called boxing.
Whereas C++ classes can be defined to have no parent, that is not possible
in Java. All Java classes must be subclasses of the root class, Object, or some
class that is a descendant of Object.
All Java objects are explicit heap dynamic. Most are allocated with the new
operator, but there is no explicit deallocation operator. Garbage collection is
Free download pdf