Saturday, 1 February 2014

Virtual Functions in Java

According to Virtual function definition: 
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.

In Java, we can override all non-static , non-private , non-final methods within an inheriting class.

According to this, All non-static functions or methods in java are virtual by default. Private and final methods or functions are not virtual in java.

Methods in Interfaces and abstract classes are pure virtual methods. Because they are declared to be overridden.

Have a look on below example
interface Shape
{
  public int setLength(); // Pure Virtual function
}

public class Circle implements Shape
{
 @Override
  public int setLength() // can be overridden, so its virtual funtion
 {
         .................
         ................
 }
}

public class Animal
{
 public static void sound() // Its not a virual, static methods cannot be overridden
 {

 }
 public final void talk() // It is not a virtual , final methoda cannot be overridden
 {
   
 }
 public void height() // It is a virtual function
 {

 }
}

public class Cat extends Animal
{
 // statements
}

Followers