How does default virtual behavior differ in C++ and Java?

JavaServer Side ProgrammingProgramming

In C++, the class member methods are non-virtual by default. This means, they can be made virtual by specifying it.

On the other hand, in Java, methods are virtual by default, and can be made non-virtual with the help of the ‘final’ keyword.

Example

 Live Demo

class base_class{
   public void display_msg(){
      System.out.println("The display_msg method of base class class");
   }
}
class derived_class extends base_class{
   public void display_msg(){
      System.out.println("The display_msg of derived class called");
   }
}
public class Main{
   public static void main(String[] args){
      base_class my_instance = new base_class();;
      my_instance.display_msg();
   }
}

Output

The display_msg method of base class class

A class named ‘base_class’ is created, that has a function ‘display_msg’. This function just displays a relevant message. Another function named ‘derived_class’ is inherited from the ‘base_class’. This class also has the ‘display_msg’ that displays the relevant message. Another class named Main contains the main function, where an instance of base_class is created. The ‘display_msg’ is called with this instance and the output is displayed on the screen.

raja
Published on 17-Aug-2020 09:22:02
Advertisements