Wednesday 25 June 2014

Is there is any Virtual keyword in Java ?

In Java there is no keyword names “virtual

Definition of Virtual method:
In object-oriented programming, a virtual function or virtual method is a function or method whose behaviour can be overridden within an inheriting class by a function with the same signature to provide the polymorphic behavior.
Therefore according to definition, every non-static method in JAVA is by default virtual method except final and private methods. The methods which cannot be inherited for polymorphic behavior is not a virtual method.


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

Question : why we say that static method is not a virtual method in Java?
Answer : static method is bound to the class itself, so calling the static method from class name or object does not provide the polymorphic behavior to the static method. We can override the static method however it will not give the advantage of the polymorphism.

No comments:

Post a Comment