Java Virtual Method

In this tutorial you will learn about java virtual method or function.

Java is a programming language which has never failed to let the programmer marvel in wonder. One such concepts of the java programming language are that of java virtual methods. Unlike other programming languages, java provides for a default support to the java virtual function.

This means, all the methods other than private and the static methods, are by default virtual methods.

Now, the question arises: what actually are the virtual methods and what contribution they give to our programming in java? To provide an answer to such questions only, this article has been framed out.

Java Virtual Method

When a Super class reference holds a subclass method, calling the same method using the super class reference will automatically call the subclass method. Thus, the Super class method actually gets hidden until we use the keyword “Super”. This means, using the keyword “Super” only will lead to calling the Super class method. Therefore, in a way the Super class method gets hidden. Hence, in an object oriented java programming, instead of the reference, we are calling the method in accordance to its object. The methods which are implementing this concept are the java virtual methods.

The prerequisites of a virtual function are:

  • Inheritance
  • Polymorphism

Example:

class Coach {
	
	//virtual method
	void per() {
		System.out.println("Coach Class");
	}
}

public class Sportscoach extends Coach {
	void per() {
		System.out.println("Sportscoach Class");
	}
	
	public static void main (String args[]) {
		Coach obj = new Sportscoach();
		obj.per();
	}
}

Output

Sportscoach Class

A virtual function essentially holds these two concepts and this is why the private and static methods are not virtual methods.

Things to Remember About Virtual Functions

  1. A virtual function in java, is just a function of any class which is defined again in the derived class. For a function to be virtual, you do not need any explicit declaration for the same.
  2. The base class pointer (also called reference) can be used to refer to the object of the derived class.
  3. During runtime, the base class pointer will be used to call derived class functions.

Need of Virtual Functions

  1. Runtime Polymorphism
  2. Invoke redefined function of the derived class through base class pointer at the runtime.

Thus, we can conclude that virtual functions are one of the simplest concepts of java language provided they are understood and implemented according to the best of our use. Also, it is an important concepts which knowingly or unknowingly is implemented by us during our programming tenure.

1 thought on “Java Virtual Method”

  1. No matter if some one searches for his required thing, so he/she
    needs to be available that in detail, therefore that thing is maintained over here.

Leave a Comment

Your email address will not be published. Required fields are marked *