learning processing

Page 433

414

Learning Processing class Cat extends Animal{ Cat() { super(); } void bark() { println("MEOW!"); } }

super() means execute code found in the parent class. Since bark() is not part of the parent class, we have to define it in the child class.

The following new terms have been introduced: • extends—This keyword is used to indicate a parent class for the class being defined. Note that classes can only extend one class. However, classes can extend classes that extend other classes, that is, Dog extends Animal, Terrier extends Dog. Everything is inherited all the way down the line. • super( )—Super calls the constructor in the parent class. In other words, whatever you do in the parent constructor, do so in the child constructor as well. This is not required, but is fairly common (assuming you want child objects to be created in the same manner as their parents). Other code can be written into the constructor in addition to super( ). A subclass can be expanded to include additional functions and properties beyond what is contained in the superclass. For example, let’s assume that a Dog object has a hair color variable in addition to age, which is set randomly in the constructor. The class would now look like so: class Dog extends Animal { color haircolor; Dog() { super(); haircolor = color(random(255)); }

A child class can introduce new variables not included in the parent.

void bark() { println("WOOF!"); } }

Note how the parent constructor is called via super( ), setting the age to 0, but the haircolor is set inside the Dog constructor itself. Suppose a Dog object eats differently than a generic Animal. Parent functions can be overridden by rewriting the function inside the subclass. class Dog extends Animal { color haircolor; Dog() { super(); haircolor = color(random(255)); } void eat() { // Code for how a dog specifically eats } void bark() { println("WOOF!"); } }

A child can override a parent function if necessary.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.