Home > Software > Java > Core-Java
Interview Questions   Tutorials   Discussions   Programs   

Core-Java - How can we have virtual functions in java?




350
views
asked marvit September 18, 2014 01:45 AM  

How can we have virtual functions in java?


           

1 Answers



 
answered By Madhumathi   0  

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.

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

flag   
   add comment

Your answer

Join with account you already have

FF

Preview


Ready to start your tutorial with us? That's great! Send us an email and we will get back to you as soon as possible!

Alert