Software & Finance





Java - Virtual Functions - No virtual keyword





In Java you do not need to use any keyword like virtual or override since by default all non static functions are considered as virual. You have to make it either private or use final keyword to remove the default virtual feature in each function in the Java classes.

 

There are 3 classes given on this example. Shape is a base class and Circle and Triangle are the classes derived from the base class Shape. The base class Shape* is used to access all two dervied class functions.

 

NOTE: No virtual or override keyword in Java.

 

 

Source Code


import java.io.*;

 

 

class Shape

{

 

    public Shape()

    {

        System.out.println("Shape");

    }

 

    public void draw()

    {

        System.out.println("Drawing Shape");

    }

}

 

 

class Circle extends Shape

{

    int r;

 

    public Circle()

    {

        System.out.println("Circle");

    }

 

    public void draw()

    {

        System.out.println("Drawing Circle");

    }

}

 

 

 

class Triangle extends Shape

{

    public int a,b,c;

 

    public Triangle()

    {

        System.out.println("Triangle");

    }

 

    public void draw()

    {

        System.out.println("Drawing Triangle");

    }

}

 

class VirtualFunctions

{

    public static void main(String[] args)

    {

            Shape[] objects = { new Shape(),

                                    new Circle(),

                                    new Triangle()

                  };

 

        System.out.println("\n\nNow Drawing Objects\n");

 

            for(int i = 0; i < 3; i++)

                  objects[i].draw(); // // This line explains the concept of polymorphism

       

 

        System.out.println("\n");

    }

}

Output


D:\Program Files\Java\jdk1.6.0_23\bin>javac VirtualFunctions.java

 

D:\Program Files\Java\jdk1.6.0_23\bin>java VirtualFunctions

Shape

Shape

Circle

Shape

Triangle

 

 

Now Drawing Objects

 

Drawing Shape

Drawing Circle

Drawing Triangle