Thursday, June 07, 2012

Interface (virtual function in C++) - Polymorphism

interface Animal
{

    String getName();   //Abstract String getName() is ok too??
    String talk();
}


class Cat implements Animal
{
    public String name;
    public Cat(String name)   //constructor
    {       
        this.name = name;
        //System.out.println(name);
    }

    public String talk()
    {
        return "Meowww!";
    }

    @Override
    public String getName() {
        // TODO Auto-generated method stub
        System.out.println("GetnameCat = " + name);
        return name;
    }
}

class Dog implements Animal
{
    public String name;
    public Dog(String name)
    {
        this.name = name;
    }

    public String talk()
    {
        return "Arf! Arf! Arf!";
    }

    @Override
    public String getName() {
        // TODO Auto-generated method stub
        System.out.println("GetnameDog = " + name);
        return name;
    }
}

class TestAnimals     //name has to be in this case with or without public is ok 
{
    // prints the following:
    //
    // Missy: Meowww!
    // Mr. Mistoffelees: Meowww!
    // Lassie: Arf! Arf!
    //
    public static void main(String[] args)
    {

              
           Animal[] animals =
        {
            new Cat("Missy"),
            new Cat("Mr. Mistoffelees"),
            new Dog("Lassie")
        };
     
//java for each Loops without index otherwise (int i; i < animals.length; i++)
              for (Animal a: animals)
            {
            System.out.println(a.getName() + ": " + a.talk());
            }
    }
//--C++ virtual function
#include <iostream>
#include <string>

using namespace std;

class Animal
{
        public:
        Animal(const string& name) : name(name) {};
        virtual string talk() = 0;  //Need pure virtual function here
        //virtual string talk();
        const string name;
};

class Cat : public Animal
{
        public:
        Cat(const string& name) : Animal(name) {};
        virtual string talk() { return "Meow!"; }
};

class Dog : public Animal
{
        public:
        Dog(const string& name) : Animal(name) {};
        virtual string talk() { return "Arf! Arf!"; }
};

// prints the following:
//
// Missy: Meow!
// Mr. Mistoffelees: Meow!
// Lassie: Arf! Arf!
//
int main()
{
        Animal* animals[] =
        {
                new Cat("Missy"),
                new Cat("Mr. Mistoffelees"),
                new Dog("Lassie")
        };

        for(int i = 0; i < 3; i++)
        {
                cout << animals[i]->name << ": " << animals[i]->talk() << endl;
                delete animals[i];
        }
        return 0;
}
UML: Generated by Umbrello: Import the code to generate the diagram or diagram to code generating it can be used to understand OOP or see how it translates between Java and C++ with very limited. It is great to study it is easy to use but not that good as Rational Rose. It is running under linux.

No comments: