×

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

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Java Implements Keyword

To understand about the keyword implements we need to learn about the concept of the interfaces and inheritance in java programming languages. So let us learn about the interface and...

3 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

Java Byte intValue() method

The intValue()  method of Java Integer class returns an int value for this Integer.  Syntax public int intValue()  Parameters NA  Specified by This method is specified by intValue in class Number  Return Value This method returns the numeric...

1 minute read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

How to convert float to String in Java

How to convert float to String in java There are following methods to convert float to String: Convert using Float.toString(float) Convert using String.valueOf(float) Convert using Float.toString(float) The Float class has a static method that returns...

2 minutes read.

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.