xxxxxxxxxx
// C++ program for function overriding
#include <bits/stdc++.h>
using namespace std;
class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
class derived:public base
{
public:
void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly
{ cout<< "print derived class" <<endl; }
void show ()
{ cout<< "show derived class" <<endl; }
};
//main function
int main()
{
base *bptr;
derived d;
bptr = &d;
//virtual function, binded at runtime (Runtime polymorphism)
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
xxxxxxxxxx
import java.io.*;
class Animal {
void eat()
{
System.out.println("eat() method of base class");
System.out.println("eating.");
}
}
class Dog extends Animal {
void eat()
{
System.out.println("eat() method of derived class");
System.out.println("Dog is eating.");
}
}
class MethodOverridingEx {
public static void main(String args[])
{
Dog d1 = new Dog();
Animal a1 = new Animal();
d1.eat();
a1.eat();
Animal animal = new Dog();
// eat() method of animal class is overridden by
// base class eat()
animal.eat();
}
}
xxxxxxxxxx
class Test
{
public:
virtual void print(){ cout << "Test Function"; }
};
class Sample : public Test
{
public:
void print(){ cout << "In Sample Function";}
};
int main()
{
Test obj = new Sample();
obj.print();
return 0;
}