×

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

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Java Lambda foreach

Before understanding lamda foreach, one must know about foreach loop in Java. foreach loop in Java Since J2SE 5.0, there has been a for-each loop in Java, also known as an extended...

4 minutes read.

Java Math scalb() Method

The scalb() method of Java Math class returns a single perfectly rounded product of floating-point and member of the double value set as if performed by d*2scaleFacor rounded value. Syntax: public static...

2 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Find Unique Elements in Array Java

An array in Java is a grouping of objects that share the same type of data. We are free to enter identical or repeating elements into an array. Therefore, we...

6 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.