MKoD - D Programming Language

Class Inheritance example in D - code-name class_inhert.d

Basic Newbie Stuff Class Inheritance Example:

// ** class_inhert.d - last tested with D v1.0
/+
 ' Class Inheritance Example
 ' --------------------------
 ' Inheritance is the ability to derive new classes from existing classes. 
 ' A derived class (or "subclass") inherits the instance variables and 
 ' methods of the "base class" (or "superclass"), and may add new instance 
 ' variables and methods. New methods may be defined with the same names as 
 ' those in the base class, in which case they override the original one.
 '
 ' To compile: C:\dmd_MKoD_ex>dmd class_inhert.d
 +/
private import std.stdio;

// Base Class
class Location  // Implicitly inherits from object
{ 
    private char[] sName;

    // The constructor that initializes Location
    this( in char[] sName ) 
    {
        writefln( "Location.this( in char[] ) constructor called. sName=\"%s\"", sName );
        this.sName = sName;
    }

    public char[] Name() 
    { 
        return sName; 
    }

    public void Display() 
    {
        std.stdio.writefln( "Location Class.Display() called. sName=\"%s\"", sName );
    }

} // end class Location

// Inherits from the Location Class
class URL : Location  
{ 
    public void Navigate() 
    {
        std.stdio.writefln( "URL Class.Navigate() called. sName=\"%s\"", sName );
    }

    // The constructor for URL, which calls Location's constructor
    this( in char[] sName ) 
    { 
        // Calls Base Class this( in char[] sName )
        super( sName ); 
    }

} // end class URL : Location

void main() 
{
    URL oURL = new URL( "http://www.digitalmars.com/d/" );
    oURL.Display();
    oURL.Navigate();

} // end void main()
C:\dmd\MKOD_ex>dmd class_inhert.d
C:\dmd\bin\..\..\dm\bin\link.exe class_inhert,,,user32+kernel32/noi;

C:\dmd\MKOD_ex>class_inhert
Location.this( in char[] ) constructor called. sName="http://www.digitalmars.com/d/"
Location Class.Display() called. sName="http://www.digitalmars.com/d/"
URL Class.Navigate() called. sName="http://www.digitalmars.com/d/"

C:\dmd\MKOD_ex>
Mars: fourth Rock from the Sun.