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”.
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 final keyword. For example, in the following java program, show() is by default virtual and the program prints “Derived::show() called”
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.
- Comparison of Exception Handling in C++ and Java
- Foreach in C++ and Java
- Comparison of Inheritance in C++ and Java
- Accessing Grandparent’s member in Java using super
- Comparison of static keyword in C++ and Java
- HashSet vs TreeSet in Java
- ShortBuffer allocate() method in Java With Examples
- IntBuffer duplicate() method in Java with Examples
- ShortBuffer compact() method in Java With Examples
- LongBuffer equals() method in Java