Let us discuss how the default virtual behavior of methods is opposite in C++ and Java. It is very important to remember that in the C++ language class member methods are non-virtual by default. They can be made virtual by using virtual keywords. For example, Base::show() is non-virtual in following program and program prints “Base::show() called”.
Example:
CPP
#include <iostream>
using namespace std;
class Base {
public:
void show()
{
cout << "Base::show() called";
}
};
class Derived : public Base {
public:
void show()
{
cout << "Derived::show() called";
}
};
int main()
{
Derived d;
Base& b = d;
b.show();
getchar();
return 0;
}
|
Output:
Base::show() called
Output Explanation: Adding virtual before definition of Base::show() makes program print “Derived::show() called”. In Java, methods are virtual by default and can be made non-virtual by using the final keyword. For example, in the following java program, show() is by default virtual and the program prints “Derived::show() called“.
Let us see what happens in the case we use the same concept in a java programming language via the example proposed below.
Example:
Java
import java.util.*;
class Base {
public void show()
{
System.out.println("Base::show() called");
}
}
class Derived extends Base {
public void show()
{
System.out.println("Derived::show() called");
}
}
public class GFG {
public static void main(String[] args)
{
Base b = new Derived();
;
b.show();
}
}
|
Output
Derived::show() called
Note: Unlike C++ non-virtual behavior, if we add final before the definition of the show() in Base, then the above program fails in the compilation.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!