Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is virtual method calling in java?

Ive saw the next paragraph in some computer science test and i'll hope i can get here a good explanation of what it means because i googled it for an hour and can't find anything..

"When we say Java language has virtual method calling we mean that in java applications the executed method is determined by the object type in run time"

What does it mean? can anyone explain it better?

like image 420
Popokoko Avatar asked Feb 26 '12 14:02

Popokoko


People also ask

What is a virtual call in Java?

Virtual function in Java is expected to be defined in the derived class. We can call the virtual function by referring to the object of the derived class using the reference or pointer of the base class. Every non-static method in Java is by default a virtual method.

What is virtual method in Java with example?

A virtual function or virtual method in an OOP language is a function or method used to override the behavior of the function in an inherited class with the same signature to achieve the polymorphism.

Can you call a virtual method?

Virtual functions allow a program to call methods that don't necessarily even exist at the moment the code is compiled. In C++, virtual methods are declared by prepending the virtual keyword to the function's declaration in the base class.

What is meant by virtual method?

What Does Virtual Method Mean? A virtual method is a declared class method that allows overriding by a method with the same derived class signature. Virtual methods are tools used to implement the polymorphism feature of an object-oriented language, such as C#.


2 Answers

The author of these lines used the c++ terminology of virtual.

A better terminology is dynamic binding / dynamic dispatch.

That means, that the object's dynamic type is "chosing" which method will be invoked, and not the static type.

For example: [pseudo code]:

class A {
  public void foo() { }
}
class B extends A { 
  public void foo() { }
}

when invoking:

A obj = new B();
obj.foo();

B.foo() will be invoked, and NOT A.foo(), since the dynamic type of obj is B.

like image 56
amit Avatar answered Oct 04 '22 23:10

amit


we mean that in java applications the executed method is determined by the object type in run time

interface Animal{
  public void eat();
}


class Person implements Animal{
   public void eat(){ System.out.println("Eating Food");}
}



class Eagle implements Animal{
   public void eat(){ System.out.println("Eating Snake");}
}

in main

Animal animal = new Person();
animal.eat(); //it will print eating food
animal = new Eagle();
animal.eat(); //it will print eating snake
like image 27
jmj Avatar answered Oct 04 '22 22:10

jmj