Storing Objects and Classes
Page 3 of 5

The People Table and Storing Subclasses

As you know, toursDB stores several kinds of serializable objects. The People table stores instances of the class JBMSTours.serializabletypes.Person.

It also stores instances of subclasses of the Person data type such as Adult and Child. Cloudscape allows you to store instances of any subclasses of a column's data type in a column.

The Adult class is identical to the Person class, except that it has an additional method, getPassportNumber (and an additional corresponding private field).

The Child class does not have the getPassportNumber method, but it has a getParentId method (and an additional corresponding private field).

Select Instances of Subclasses from the Person Table

  1. Close the connection to HelloWorldDB:

    disconnect;

  2. Open a connection to toursDB:

    connect 'toursDB';

  3. Turn off auto-commit:

    autocommit off;

    You may remember this insert statement from Lesson 6, "Working with SQL-J's Java Extensions":

    (Don't do the insert, just look at it . . .)

    -- Person is an alias for JBMSTours.serializabletypes.Person.
    INSERT INTO people (person) VALUES (new Person('Your', 'Name'));

  4. Try finding out the passport numbers of all the people in the People table:

    SELECT person.getPassportNumber() FROM People;

    You should get an error message like the following:

    ERROR 42X50: No method was found with the
    signature JBMSTours.serializabletypes.Person.getPassportNumber().
    It may be that the method exists, but it is
    not public, or that the parameter types
    are not method invocation convertible.

    You get the error because the Person class (the data type of the column) does not have a method of that signature.

    Quiz: How do you access that method on the adults?

    Answer: Cast the data type of the Person column to Adult (an alias for JBMSTours.serializabletypes.Adult).

    The CAST operator lets you force one data type to be interpreted as another data type. For Java data types, such casts follow the same rules as explicit casts in Java.

  5. Now try the same query with the CAST operator:

    SELECT (CAST
        (person as Adult)).getPassportNumber()
    FROM People;

    SQLCol1
    -----------
    ABC-DE-FGHX
    unknown
    ERROR XCL12: An attempt was made to put a data
    value of type 'JBMSTours.serializabletypes.Child'
    into a data value of type 'JBMSTours.serializabletypes.Adult'.

  6. The table contains instances of the class Child as well as the class Adult, and a CAST from the Child data type to an Adult data type is not supported. So to select only the appropriate rows on which to invoke the method, use the INSTANCEOF operator. This operator tests for the data type of an object.

    SELECT (CAST (person AS Adult)).getPassportNumber()
    FROM People
    WHERE person INSTANCEOF Adult;

    Now you should be able to get some results.

  7. Exit ij.