Inheritance

From FizzFuzz

Jump to: navigation, search

Inheritance is a common aspect of object-oriented programming, which involves a superclass (often called the "parent") passing variables and methods to the subclass (often called the "child").

Setting A Subclass

A subclass is indicated by using the inherit keyword.

//Defines the superclass.
class superclass
 
class subclass
    inherit superclass

Modifying A Subclass

A subclass is modified by writing either the variables or methods as one normally would, but forsaking the access modifiers or data types.

//Defines the superclass class.
class superclass
    //Creates a few variables and methods, which will be
    //passed to the subclass.
    integer a = 1, b = 2, c = 3
 
    integer a_value()
        return a
 
    integer b_value()
        return b
 
    integer c_value()
        return c
 
//The subclass class, which inherits from superclass.
class subclass
    //Indicates the class it inherits from.
    inherit superclass
 
    //As these values have been defined before, they are
    //written without a data type, to indicate modification.
    a = 2
    b = 4
    c = 6
 
    //a_value() has been defined before, so it is written
    //without a data type.
    a_value()
        return a * 2
 
    //Defines a new method.
    integer sum_value()
        return a + b + c
 
//A new class, which inherits from subclass. In this case,
//subclass is the parent and superclass is the grandparent,
//though subclass is the superclass to derived_subclass.
class derived_subclass
    //Inherits from subclass.
    inherit subclass
 
    //These all existed for superclass, so it inherits them
    //from subclass.
    a = 4
    b = 8
    c = 12
 
    //Defines a new variable.
    integer d = 16
 
    //Modifies the sum_value() method from subclass.
    sum_value()
        return a + b + c + d

Calling Superclass Methods and Variables

Superclass variables methods can be referred to by using the parent keyword. This will refer to the default value of variables, and will also call superclass methods.

#include <std.dflt.*>
 
//Defines the superclass.
class superclass
    void Output(string s)
        environment.outputln(s)
 
//Defines the subclass.
class subclass
    //Inherits from superclass.
    inherit superclass
 
    //Modifies the Output() method.
    Output(string s, string p)
        if(p)
            environment.outputln("[p]: [s]")
        else
            //Calls the actions of the parent's method,
            //with the appropriate arguments.
            parent.Output(s)
Personal tools
Navigation
functions
language