Links

Categories

Tags


« | Main | »

Classes and interfaces

By Jewe | October 29, 2012

// define an interface
interface Person
{
    method string Name();
    method int Age();
}

// implement this interface
class Clerk implements Person
{
    method Clerk(string n, int a)
    {
        name = n;
        age = a;
    }
    method string Name()
    {
        return name;
    }
    method int Age()
    {
        return age;
    }
    method AddExtraHours(int hours)
    {
    }
    method Underpay(int numBucks)
    {
    }
    string name;
    int age;
}

// another implementation
class Boss implements Person
{
    method Boss(string n, int a)
    {
        name = n;
        age = a;
    }
    method string Name()
    {
        return name;
    }
    method int Age()
    {
        return age;
    }
    method AddPriviledges(int numPriviledges)
    {
    }
    method Overpay(int numBucks)
    {
    }
    string name;
    int age;
}

function main()
{
    // create two persons
    Person p1 = new Clerk("Waldorf", 34);
    Person p2 = new Boss("Stadler", 45);

    // print both
    println("p1.Name:  " + p1.Name());
    println("p1.Age:   " + p1.Age());
    println("p2.Name:  " + p2.Name());
    println("p2.Age:   " + p2.Age());

    // swap them!
    { Person p = p1; p1 = p2; p2 = p; }

    // to access members not in the interface (this adds a run-time check)
    p1.Boss::Overpay(1500);
    p2.Clerk::Underpay(100);

    // to cast down the references (this adds a run-time check)
    Boss b = (Boss) p1;
    Clerk c = (Clerk) p2;
}

Topics: code examples | Comments Off on Classes and interfaces

Comments are closed.