×

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same syntax to create polymorphism.

The location of a virtual function in a Programming language is a problem for developers switching over from C++ to Java. The virtual function is specified in C++ using the virtual keyword. However, Java implements it differently. In C++, view Virtual function.

Object-oriented programming Java supports OOPs concepts like polymorphism, inheritance, encapsulation, etc. Objects, classes, and member functions are the foundation for all these ideas. Except for final, static, and private functions, which can be used to enable polymorphism, most example methods in Java are regarded as related to creating by default.

How the virtual function can be used in Java

Java does not use virtual keywords to define virtual methods; rather, the virtual functions and methods are implemented by using different methodologies:

  • We may replace the virtual function with the inherited class method to use the same name. Typically, the parental class defines the virtual function, and the inheriting class overrides it.
  • A class name is where the virtual function is expected to be implemented. Using the connection or pointer from the class name, we can access it by pointing to the item of the subclass.
  • The title and arguments of a virtual function must be identical in both the base class and any derived classes.
  • An IS-A association used to specify the class structure in inherited is required again for virtual function.
  • Since private functions cannot be modified, the virtual function can sometimes be private.
  • Since final methods could become overridden, a virtual function or a  method could not be finalised.
  • A virtual method shouldn't be static because static functions can't be overridden.
  • Each non-static method within Java is defined as a virtual function.
  • Implementing oops principles like real-time polymorphism by using virtual functions is possible.

Consider a small program for better understanding:

Example:

Dog.java

import java.io.*;
import java.util.*;
//Parent class  
class Animal {  
void eating() //declaring the eating() function  
{  
System.out.println("In the Animal class");  
}  
}  




public class Dog extends Animal // Inheriting the Parent Class
{  
    void eating() // The function eating() is overrided from the Parent(Animal) class  
   {  
      System.out.println("This is the Dog class");  
   }  
   public static void main(String args[]){  
   Animal obj1 = new Dog(); //By using Animal class the child class(Dog) is get referenced 
   obj1.eating();  
  }  
}  

Output

Virtual Function in Java

In the above example program, the virtual function eating() is used for overriding the Dog class.

Every accessible, non-static, and non-final procedure in  Java is a virtual function. Polymorphism can be obtained by using these techniques. The techniques for achieving polymorphism could never be virtual functions.

The virtual function should not be a fixed, final, or private method. The class or object names could be used to call a static method. Although if we attempt, it will not be capable of achieving the polymorphism.

Java Interface as a Virtual function

In Java, a class types template known as an interface contains static variables and abstraction methods. Since the following classes provide the method implementations, all Java connections are treated as virtual functions.

The below example is about the interface:

Example:

interface Vehicle{    
void display();    
}    
public class Alto implements Vehicle{    
public void display()
{
System.out.println("Alto car");
}    
public static void main(String args[]){    
Alto obj = new Alto();    
obj.display();    
 }    
}    

Output:

Virtual Function in Java

The above example can execute the interface method by implementing the Alto class.

Pure Virtual Function

Derived class function refers to a virtual function we do not need to implement. For instance, Java's Abstraction method is indeed a wholly virtual function.

The below example will describe the Pure Virtual Function:

Example:

Demo.java

abstract class Teacher {  
        final void teaching() //method of abstract class
        {  
        System.out.println("1 st teacher");  
        }  
        abstract void explain(); // it is the pure abstract method 
}  
    class Principal extends Teacher //Parent class is the Principal
        {  
        void explain(){  
        System.out.println("My teacher is explaining well");  
        }  
}  
public class Demo  //main class
      {  
        public static void main(String args[]){  
        Teacher obj = new Principal();  //an object obj is created for Demo class
        obj.explain();  
        }  
        }  

Output:

Virtual Function in Java

The explain() method in the above program is the pure virtual function.

Runtime Polymorphism

A call to a function that has been overridden is processed through runtime polymorphism instead of compilation time. Rather than a reference variable when using dynamic polymorphism, a function will be called. Dynamic polymorphism could be accomplished using virtual functions.

Example:

Placements.java

class Programming{  
public void display() // it is the virtual function in class Programming
{  
System.out.println("welcome to this world");  
}  
}  
public class Placements extends Programming{  
public void display() // the method of child class(Placements)
{  
System.out.println("The best method for cracking placements.");  
}  
public static void main(String args[]){  
Programming obj = new Placements();  //an object obj is created
obj.display();  
}}  

Output

Virtual Function in Java

From the program above, we can use the Virtual function for dynamic Polymorphism.

Overview:

Consider these factors when using Java's Virtual function:

  • The Virtual Function is a typical Java method.
  • To design the virtual function, we aren't supposed to declare any specific description.
  • Java does not use virtualised keywords to specify the imaginary function.
  • The virtual function must be created in the subclass using the same title in the parent class, and the parent class reference is employed to refer to an object of the derived classes.
  • Except for final, static, and private functions, all Java prototype methodologies are considered virtual functions.

Related Topics

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Difference between final, finally, and finalize()

Difference between final, finally, and finalize() In Java, final, finally and finalize sound similar they are totally different in functionality. Final and finally are the two keywords but the finalize is...

4 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

Java Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Process and Thread in Java

Process It is a program that is running on your computer. The process is a heavy-weight, which takes memory separately to other processes. The process may be a small background task like spell-checker; it...

11 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.