Jan 15, 2009

virtual function in c++ and java

In C++ virtual function has the following meaning:
"A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function."
In java, you don't need to declare a method as virtual. This is the default behaviour. If you don't want a function to be virtual you declare it as final in java. In java if you define a method in descendent with the same signature as in ancestor then it automatically overrides the ancestor method.

public class Animal {
public void eat() { System.out.println("I eat like a generic Animal."); }

public static void main(String[] args) {
Animal[] anAnimal = new Animal[4];

anAnimal[0] = new Animal();
anAnimal[1] = new Wolf();
anAnimal[2] = new Fish();
anAnimal[3] = new OtherAnimal();

for (int i = 0; i < 4; i++) {
anAnimal[i].eat();
}
}
}

public class Wolf extends Animal {
public void eat() { System.out.println("I eat like a wolf!"); }
}

public class Fish extends Animal {
public void eat() { System.out.println("I eat like a fish!"); }
}

public class OtherAnimal extends Animal {}

I eat like a generic Animal.
I eat like a wolf!
I eat like a fish!
I eat like a generic Animal.

No comments:

Post a Comment