Java Intro Class

Subclassing and Inheritance

Our "pencil" applet says "class pencil extends Applet". The "extends" really means that pencil objects are a type of Applet object with some added features. In Java terms, "pencil" is a "subclass" of "Applet". Why would you want to do something like that? Remember how we learned that the browser JVM calls a bunch of special entry points in applets? Why aren't they in our pencil applet? Short answer - they are!

When the JVM creates an object from a subclass, it first creates an object of the "superclass" ("Applet" in this case.) then adds the data and methods of the subclass to that object to make it into an object of the subclass type. That means that every object of a subclass type is also an object of the "superclass" type and has all of it's data items and methods included. Therefore our applet has all the entry points (methods) for an Applet whether we use them or not. The one we defined (mouseDrag) "overrides" the one defined in the Applet superclass. The other ones do very little by default in this case, but in the general case make an extension class much more powerful than just it's own code provides.

Note that if you don't specify that your class extends another class, the default is to extend the builtin "object" class. This makes every Java object also of type "object". Maybe that's why they call them "objects"! The subclass terminology applied to objects is that a subclass object is a "child" of the "parent" superclass object and is said to "inherit" the properties (data fields/methods) of the parent object. The rules for overriding data and methods in subclasses or accessing them in superclasses are complex and we will not cover them in this introductory class.