Default virtual behavior of methods is opposite in C++ and Java:

In C++, class member methods are non-virtual by default. They can be made virtual by using virtual keyword. For example, Base::show() is non-virtual in following program and program prints“Base::show() called”.

在c++中,类的成员方法默认是非虚函数,因此想要变为虚函数必须被显式地添加virtual关键字

#include<iostream>
 
using namespace std;
 
class Base {
public :     
 
     // non-virtual by default
     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;
}

Adding virtual before definition of Base::show() makes program print “Derived::show() called”

上述程序的是打印结果是"Base::show() called",如果在基类的show函数之前添加了virtual关键字,则将打印出"Derived::show() called"

In Java, methods are virtual by default and can be made non-virtual by using final keyword. For example, in the following java program, show() is by default virtual and the program prints“Derived::show() called”

Java中如果想要令一个函数变成non-virtual必须显式地添加final关键字,但是一旦添加了这个关键字就意味着子类无法重载这个函数了

class Base {
 
     // virtual by default
     public void show() {
        System.out.println( "Base::show() called" );
     }
}
 
class Derived extends Base {
     public void show() {
        System.out.println( "Derived::show() called" );
     }
}
 
public class Main {
     public static void main(String[] args) {
         Base b = new Derived();;
         b.show();
     }
}

Unlike C++ non-virtual behavior, if we add final before definition of show() in Base , then the above program fails in compilation.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.